简体   繁体   English

将列表视图中的多个数据插入UWP上的数据库

[英]Insert multiple data from listview to database on UWP

I have 2 listview named "updateList" and "selectedUpdateList" and a "uuthemis.db" database. 我有2个名为“updateList”和“selectedUpdateList”的listview和一个“uuthemis.db”数据库。 "updateList" listview contains data from json and is multiple selection, while "selectedUpdateList" listview contains data selected by the user from "updateList" listview. “updateList”listview包含来自json的数据并且是多选,而“selectedUpdateList”listview包含用户从“u​​pdateList”listview中选择的数据。

JSON: JSON:

{
idfile: "1139",
judul: "PP No 30 Th 2016 - Pemindahan Ibu Kota Kabupaten Nias Dari Wilayah Kota Gunungsitoli Ke Wilayah Kecamatan Gido Kabupaten Nias Provinsi Sumatera Utara",
path: "http://...../uupp/2016/PP/",
tgl: "2016-11-11 14:31:35",
destination: "FileUU/04 - Peraturan Pemerintah (PP)",
root: "2016",
file: "PP_No_30_Th_2016.pdf",
},
{
idfile: "1140",
judul: "PP No 31 Th 2016 - Kawasan Ekonomi Khusus Sorong",
path: "http://...../uupp/2016/PP/",
tgl: "2016-11-11 14:32:07",
destination: "FileUU/04 - Peraturan Pemerintah (PP)",
root: "2016",
file: "PP_No_31_Th_2016.pdf",
},
{
idfile: "1141",
judul: "PP No 75 Th 2015 - Jenis Dan Tarif Atas Jenis Penerimaan Negara Bukan Pajak Yang Berlaku Pada Kementerian Kelautan Dan Perikanan",
path: "http://...../uupp/2015/PP/",
tgl: "2016-11-11 14:33:16",
destination: "FileUU/04 - Peraturan Pemerintah (PP)",
root: "2015",
file: "PP_No_75_Th_2015.pdf",
},
{
idfile: "1142",
judul: "PP No 76 Th 2015 - Perubahan Atas Peraturan Pemerintah Nomor 101 Tahun 2012 Tentang Penerima Bantuan Iuran Jaminan Kesehatan",
path: "http://...../uupp/2015/PP/",
tgl: "2016-11-11 14:33:41",
destination: "FileUU/04 - Peraturan Pemerintah (PP)",
root: "2015",
file: "PP_No_76_Th_2015.pdf",
},
{
idfile: "1143",
judul: "PP No 77 Th 2015 - Penggabungan Perusahaan Perseroan PT Reasuransi Umum Indonesia Ke Dalam Perusahaan PT Reasuransi Indonesia Utama",
path: "http://...../uupp/2015/PP/",
tgl: "2016-11-11 14:34:02",
destination: "FileUU/04 - Peraturan Pemerintah (PP)",
root: "2015",
file: "PP_No_77_Th_2015.pdf",
}

XAML: XAML:

<Button x:Name="downloadBtn" Grid.Column="2" Grid.RowSpan="2" Margin="0,0,30,0" Content="Download" HorizontalAlignment="Right" Foreground="White" BorderBrush="White" BorderThickness="1" FontSize="20" FontFamily="Segoe UI Black" Click="DownloadBtn_Click"/>    
<ListView x:Name="updateList" Grid.ColumnSpan="2" Grid.Row="1" Margin="20,20,20,20"
                          AutomationProperties.AutomationId="ItemsListView"
                          AutomationProperties.Name="Items"
                          ItemsSource="{Binding updateDatas}"
                          HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                          ScrollViewer.VerticalScrollBarVisibility="Visible"
                          IsSwipeEnabled="False" SelectionMode="Multiple"
                          IsItemClickEnabled="True" IsMultiSelectCheckBoxEnabled="True" ItemClick="UpdateList_ItemClick">

                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <Grid Margin="0,20,0,0" HorizontalAlignment="Stretch" Background="{x:Null}">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="auto"/>
                                    <ColumnDefinition Width="auto"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>

                                <Image Grid.Column="1" Height="110" Width="168" Source="images/folder2.png" />

                                <TextBlock Margin="0,0,10,0" Text="{Binding ID}" Grid.Row="0" Foreground="Black" FontSize="17" VerticalAlignment="Top" HorizontalAlignment="Left" Height="auto" FontFamily="Segoe UI Black" TextWrapping="Wrap" TextAlignment="Justify" FontWeight="SemiBold" Visibility="Collapsed"/>
                                <ScrollViewer Grid.Column="2" VerticalAlignment="Top" HorizontalAlignment="Left" Height="95" Background="{x:Null}" Margin="10,5,0,0" VerticalScrollBarVisibility="Auto">
                                    <TextBlock Margin="0,0,10,0" Text="{Binding Judul}" Grid.Row="0" Foreground="Black" FontSize="17" VerticalAlignment="Top" HorizontalAlignment="Left" Height="auto" FontFamily="Segoe UI Black" TextWrapping="Wrap" TextAlignment="Justify" FontWeight="SemiBold"/>
                                </ScrollViewer>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>

                    <ListView.ItemContainerStyle>
                        <Style TargetType="ListViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                        </Style>
                    </ListView.ItemContainerStyle>
                </ListView>

                <ListView x:Name="selectedUpdateList" Grid.ColumnSpan="2" Grid.Row="1" Margin="20,20,20,20"
                          AutomationProperties.AutomationId="ItemsListView"
                          AutomationProperties.Name="Items" Visibility="Collapsed"
                          ItemsSource="{Binding selectedData}"
                          HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                          ScrollViewer.VerticalScrollBarVisibility="Visible"
                          IsSwipeEnabled="False"
                          IsItemClickEnabled="False" IsTapEnabled="False">

                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <Grid Margin="0,20,0,0" HorizontalAlignment="Stretch" Background="{x:Null}">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="auto"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>

                                <Image Grid.Column="0" Height="110" Width="168" Source="images/folder2.png" />

                                <TextBlock Margin="0,0,10,0" Text="{Binding ID}" Grid.Row="0" Foreground="Black" FontSize="17" VerticalAlignment="Top" HorizontalAlignment="Left" Height="auto" FontFamily="Segoe UI Black" TextWrapping="Wrap" TextAlignment="Justify" FontWeight="SemiBold" Visibility="Collapsed"/>
                                <Grid Grid.Column="1" Margin="10,5,0,0">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="auto"/>
                                        <RowDefinition Height="auto"/>
                                        <RowDefinition Height="auto"/>
                                    </Grid.RowDefinitions>

                                    <ScrollViewer Grid.Row="0" Margin="0,0,5,5" VerticalAlignment="Top" HorizontalAlignment="Left" Height="45" Background="{x:Null}" VerticalScrollBarVisibility="Auto">
                                        <TextBlock Margin="0,0,10,10" Text="{Binding Judul}" Grid.Row="0" Foreground="Black" FontSize="17" VerticalAlignment="Top" HorizontalAlignment="Left" Height="auto" FontFamily="Segoe UI Black" TextWrapping="Wrap" TextAlignment="Justify" FontWeight="SemiBold"/>
                                    </ScrollViewer>

                                    <ProgressBar x:Name="downloadProgress" Grid.Row="1" Margin="10,10,10,0" Value="{Binding progressBar}" Height="25" HorizontalAlignment="Stretch" IsIndeterminate="True" Background="White" BorderBrush="Black" BorderThickness="1" Foreground="#FF790F0F"/>
                                    <TextBlock x:Name="progressText" Grid.Row="2" Margin="10,0,0,0" Text="{Binding progressText}" FontSize="16"/>
                                </Grid>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>

                    <ListView.ItemContainerStyle>
                        <Style TargetType="ListViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                        </Style>
                    </ListView.ItemContainerStyle>
                </ListView>

Code: 码:

SQLiteConnection objConnUpdate = new SQLiteConnection("uuthemis.db");
        ObservableCollection<UpdateData> DataUpate = new ObservableCollection<UpdateData>();
        private UpdateData itemDetail = null;
    try
                    {
                        loading.IsActive = true;

                        string urlPath = "http://..../fetchupdate";
                        var httpClient = new HttpClient(new HttpClientHandler());
                        var values = new List<KeyValuePair<string, string>>
                        {

                        };

                        var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
                        response.EnsureSuccessStatusCode();


                        string jsonText = await response.Content.ReadAsStringAsync();
                        JsonArray jsonArray = JsonArray.Parse(jsonText);
                        foreach (JsonValue groupValue in jsonArray)
                        {
                            JsonObject groupObject = groupValue.GetObject();
                            string idfile = groupObject["idfile"].GetString();
                            string judul = groupObject["judul"].GetString();
                            UpdateData update = new UpdateData();
                            update.ID = idfile;
                            update.Judul = judul;

                            if (!dbItems.Contains(update.Judul.Split('-')[0].TrimEnd()))
                            {
                                DataUpate.Add(update);
                            }
                        }

                        updateList.ItemsSource = DataUpate;
                    }
                    catch (HttpRequestException ex)
                    {

                    }
private void UpdateList_ItemClick(object sender, ItemClickEventArgs e)
        {
            UpdateData itemClicked = ((UpdateData)e.ClickedItem);
            uuID = itemClicked.ID;
            uuName = itemClicked.Judul;
            uuPath = itemClicked.Path;
            uuRoot = itemClicked.Root;
            fileName = itemClicked.File;
            uuUrl = uuPath + fileName;

            if(!selectedUpdateList.Items.Contains(itemClicked))
            {
                selectedData.Add(itemClicked);
            }
            else
            {
                selectedData.Remove(itemClicked);
            }
            selectedUpdateList.ItemsSource = selectedData;
        }

private async void DownloadBtn_Click(object sender, RoutedEventArgs e)
        {
string splitName = uuName.Split('-')[0].TrimEnd();
if (uuName.ToLower().Contains("pp no"))
                    {}
                        var folderID = 106;

                        while (!splitName.Contains($"{2125 - folderID}") && folderID <= 181)
                            folderID++;

                        string update = @"INSERT INTO undangundang (uu_id, folder_id, identifier, filename, folder_parent_id) SELECT null, " + folderID + ",'" + uuName.Split('-')[0].TrimEnd().ToUpper() + "'," +
                        "'" + uuName.Replace(" ", "_") + ".pdf',4 WHERE not exists (select uu_id and folder_id and identifier and filename and folder_parent_id FROM undangundang where uu_id=null and folder_id=" + folderID +
                        " and identifier='" + uuName.Split('-')[0].TrimEnd().ToUpper() + "' and filename ='" + uuName.Replace(" ", "_") + ".pdf' and folder_parent_id=4)";
                        var updateQuery = objConnUpdate.Prepare(update);
                        Debug.WriteLine("sql: " + update);
                        updateQuery.Step();
                    }
}

I have a problem, if the item selected in the "updateList" listview is more than one, then the data that was successfully entered into the database is only the last 1 data is selected in updateList. 我有一个问题,如果在“updateList”列表视图中选择的项目多于一个,那么成功输入数据库的数据只是在updateList中选择的最后一个数据。 How to handle it? 怎么处理?

Note: 注意:

"while" is used because folderID is taken automatically. 使用“while”是因为folderID是自动获取的。 For example the title on json before the "-" character contains 2019, then folderID = 106, if 2018, then folderID = 107, if 2017, then folderID = 108, etc. 例如,“ - ”字符前面的json上的标题包含2019,然后是folderID = 106,如果是2018,那么folderID = 107,如果是2017,则是folderID = 108,等等。

I checked DownloadBtn_Click method, However you just insert data with global property such as uuName , and those property will only record the last value. 我检查了DownloadBtn_Click方法,但是你只需要插入具有全局属性的数据,例如uuName ,那些属性只会记录最后一个值。 If your want to insert selectedUpdateList items, you could for-each items then insert to database. 如果要插入selectedUpdateList项,则可以将每个项插入到数据库中。

foreach (var item in selectedData)
{
    string update = @"INSERT INTO undangundang (uu_id, folder_id, identifier, filename, folder_parent_id) SELECT null, " + folderID + ",'" + item.Judul.Split('-')[0].TrimEnd().ToUpper() + "'," +
                           "'" + item.Judul.Replace(" ", "_") + ".pdf',4 WHERE not exists (select uu_id and folder_id and identifier and filename and folder_parent_id FROM undangundang where uu_id=null and folder_id=" + folderID +
                           " and identifier='" + item.Judul.Split('-')[0].TrimEnd().ToUpper() + "' and filename ='" + item.Judul.Replace(" ", "_") + ".pdf' and folder_parent_id=4)";
    var updateQuery = objConnUpdate.Prepare(update);
    Debug.WriteLine("sql: " + update);             
}
updateQuery.Step();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM