在UWP上将多个项目ListView插入数据库

时间:2019-03-21 02:18:00

标签: c# sqlite listview uwp

我有两个名为“ updateList”和“ selectedUpdateList”的列表视图,以及一个“ undangundang.db”数据库。 “ updateList”列表视图包含来自json的数据,并且是多个选择,而“ selectedUpdateList”列表视图包含用户从“ updateList”列表视图中选择的数据。

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",
}

我希望用户单击下载按钮,并且如果JSON中的“ judul”包含单词“ 2019”,它将以folder_id = 2将数据插入到“ undangundang.db”,如果包含单词“ 2018”,它将插入folder_id = 3的数据,依此类推,直到包含单词“ 1945”的数据,它将添加folder_id = 76的数据。

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,10,20,20"
                              AutomationProperties.AutomationId="ItemsListView"
                              AutomationProperties.Name="Items"
                              ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
                              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>

                                    <!--<CheckBox Grid.Column="0" />-->
                                    <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,10,20,20"
                              AutomationProperties.AutomationId="ItemsListView"
                              AutomationProperties.Name="Items" Visibility="Collapsed"
                              ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
                              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" 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="Menghitung...." FontSize="16"/>
                                    </Grid>
                                </Grid>
                            </DataTemplate>
                        </ListView.ItemTemplate>

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

代码:

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)
            {
                itemDetail = e.ClickedItem as UpdateData;
                if (e.ClickedItem is UpdateData selectedItem)
                {
                    selectedItem.IsSelected = !selectedItem.IsSelected;
                    if (selectedItem.IsSelected == true)
                    {
                        itemDetail.Judul = selectedItem.Judul;
                        itemDetail.ID = selectedItem.ID;
                        selectedData.Add(itemDetail);
                    }
                    else
                    {
                        itemDetail.Judul = selectedItem.Judul;
                        itemDetail.ID = selectedItem.ID;
                        selectedData.Remove(itemDetail);
                    }
                }
            }

            private async void DownloadBtn_Click(object sender, RoutedEventArgs e)
            {
                if (updateList.SelectedItems.Count != 0)
                {
                        var folderID = 2;

                        while (!itemDetail.Judul.Contains($"{2021 - folderID}") && folderID <= 76)
                            folderID++;

                            string update = @"INSERT INTO undangundang (uu_id, folder_id, identifier, filename, folder_parent_id) SELECT null, " + folderID + ",'" + itemDetail.Judul.Split('-')[0].TrimEnd() + "'," +
                            "'" + itemDetail.Judul.Replace(" ","_") + ".pdf',2 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='" + itemDetail.Judul.Split('-')[0].TrimEnd() + "' and filename ='" + itemDetail.Judul.Replace(" ", "_") + ".pdf' and folder_parent_id=2)";
                            var updateQuery = objConnUpdate.Prepare(update);
                            Debug.WriteLine("sql: " + update);
                            updateQuery.Step();
                    }
    }

我有一个问题,如果在“ updateList”列表视图中选择的项目不止一个,那么成功输入数据库的数据只是选择的第一个数据。如何处理?

0 个答案:

没有答案