清除WPF中的DataGrid数据

huangapple go评论59阅读模式
英文:

Clear DataGrid data in WPF

问题

因为我想要有复选框列,所以我在我的XAML中使用了以下方式创建复选框:

<DataGrid x:Name="boxNoDetail" IsReadOnly="true" ItemsSource="{Binding}" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" FontSize="12">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Checked" Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}">
            <DataGridCheckBoxColumn.ElementStyle>
                <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type CheckBox}}">
                    <Setter Property="VerticalAlignment" Value="Center"/>
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                    <Setter Property="IsHitTestVisible" Value="False"/>
                    <!-- 'read only -->
                </Style>
            </DataGridCheckBoxColumn.ElementStyle>
        </DataGridCheckBoxColumn>
    </DataGrid.Columns>
</DataGrid>

我使用以下方式绑定GridView:

Function dtFillDatagrid(ByVal dt As DataTable, ByVal dgv As DataGrid) As Boolean
    dgv.ItemsSource = Nothing
    Dim myUI As userInterface = New userInterface

    Try
        For Each column As DataColumn In dt.Columns
            Dim name As String = column.ColumnName
            If name = "IsSelected" Then
            ElseIf name = "sn" Then
                dgv.Columns.Add(myUI.DataGridText(name, name, True))            
            Else
                dgv.Columns.Add(myUI.DataGridText(name, name))
            End If
        Next
        dgv.ItemsSource = dt.DefaultView
        dgv.AutoGenerateColumns = False
        dgv.CanUserAddRows = False
        Return True
    Catch ex As Exception
        logUtil.e(ex)
        Return False
    End Try
End Function

Public Class userInterface
    Function DataGridText(ByVal bind_name As String, ByVal headerName As String, 
                          Optional notVisible As Boolean = False, 
                          Optional rightAlignment As Boolean = False) As DataGridTextColumn
        Dim col_data As DataGridTextColumn = New DataGridTextColumn
        Dim c As New Style
        col_data.Binding = New Binding(bind_name)
        col_data.Header = headerName
        If notVisible Then col_data.Visibility = Visibility.Hidden
        If rightAlignment Then
            c.Setters.Add(New Setter(TextBox.TextAlignmentProperty, TextAlignment.Right))
            col_data.CellStyle = c
        End If
        Return col_data
    End Function
End Class

如果我刷新数据(通过再次运行dtFillDatagrid()),数据表格的列会显示两次。为什么会这样?

我尝试逐步检测,发现dgv.ItemsSource = Nothing 只是清除了数据表格的数据,但没有清除字段。

我想要询问,如何使用DTFILLDATAGRID()重复,并解决重复列的问题,或者是否更方便使用DataTable来填充GridView?

首次加载GridView:
清除WPF中的DataGrid数据

第二次加载GridView:
清除WPF中的DataGrid数据

英文:

Because I want have checkbox column, I use this way create checkbox
in my XAML:

&lt;DataGrid x:Name=&quot;boxNoDetail&quot; IsReadOnly=&quot;true&quot; ItemsSource=&quot;{Binding}&quot; HorizontalScrollBarVisibility=&quot;Auto&quot; VerticalScrollBarVisibility=&quot;Auto&quot; FontSize=&quot;12&quot;  &gt;
    &lt;DataGrid.Columns &gt;
         &lt;DataGridCheckBoxColumn Header=&quot;Checked&quot;   Binding=&quot;{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}&quot;  &gt;
                  &lt;DataGridCheckBoxColumn.ElementStyle&gt;
                         &lt;Style TargetType=&quot;{x:Type CheckBox}&quot; BasedOn=&quot;{StaticResource {x:Type CheckBox}}&quot;  &gt;
                                    &lt;Setter Property=&quot;VerticalAlignment&quot; Value=&quot;Center&quot;/&gt;
                                    &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt;
                                    &lt;Setter Property=&quot;IsHitTestVisible&quot; Value=&quot;False&quot;/&gt;
                                                                    &lt;!--&#39;read only--&gt;
                                                                &lt;/Style&gt;
                   &lt;/DataGridCheckBoxColumn.ElementStyle&gt;
         &lt;/DataGridCheckBoxColumn&gt;
    &lt;/DataGrid.Columns&gt;
&lt;/DataGrid&gt;

I use this way to bind gridview:

  Function dtFillDatagrid(ByVal dt As DataTable, ByVal dgv As DataGrid) As Boolean
        dgv.ItemsSource = nothing
        Dim myUI As userInterface = New userInterface

        Try
            For Each column As DataColumn In dt.Columns
                Dim name As String = column.ColumnName
                If name = &quot;IsSelected&quot; Then
                ElseIf name = &quot;sn&quot; Then
                    dgv.Columns.Add(myUI.DataGridText(name, name, True))            
                Else
                    dgv.Columns.Add(myUI.DataGridText(name, name))
                End If

            Next
            dgv.ItemsSource = dt.DefaultView
            dgv.AutoGenerateColumns = False
            dgv.CanUserAddRows = False
            Return True
        Catch ex As Exception
            logUtil.e(ex)
            Return False
        End Try

    End Function


Public Class userInterface
Function DataGridText(ByVal bind_name As String, ByVal headerName As String, 
                      Optional notVisible As Boolean = False, 
                      Optional rightAlignment As Boolean = False) As DataGridTextColumn
        Dim col_data As DataGridTextColumn = New DataGridTextColumn
        Dim c As New Style
        col_data.Binding = New Binding(bind_name)
        col_data.Header = headerName
        If notVisible Then col_data.Visibility = Visibility.Hidden
        If rightAlignment Then
            c.Setters.Add(New Setter(TextBox.TextAlignmentProperty, TextAlignment.Right))
            col_data.CellStyle = c
        End If
        Return col_data
    End Function
end class

If I refresh the data (by running dtFillDatagrid() again), the datagrid's columns are displayed 2 times. Why ???

I tried to detect step by step, and found that dgv.Itemssource = Nothing is just clear gridview data, and there is no clear field.

I want to ask, how can I use DTFILLDATAGRID() repeatedly and solve the problem of rduplicate columns, or is it more convenient for DataTable Fill to gridView?

first load gridview:
清除WPF中的DataGrid数据

second load gridview:
清除WPF中的DataGrid数据

答案1

得分: 0

由于您指定了 dgv.AutoGenerateColumns = False,列将手动指定,您在以下位置进行了指定:

  1. 在XAML中:DataGrid.Columns。在这里,您创建了第一列,即DataGridCheckBoxColumn。
  2. dtFillDatagrid 中,使用您的 DataGridText 函数添加新列。

您只需要定义列一次。在您当前的代码中,每次执行 dtFillDatagrid 时都会添加DataGridTextColumns:

dgv.Columns.Add(myUI.DataGridText(name, name))

您应该调整代码,在窗口初始化时单独创建列。

如果您的DataTable (dt.Columns) 中的列可能每次运行 dtFillDatagrid 时都会变化,那么您可以删除除了 DataGridCheckBoxColumn(通过检查列的 Header 值)之外的所有列,然后像您现在所做的那样添加新列。只需将此代码添加到 dtFillDatagrid 中,在再次添加列之前:

Dim columnsToRemove As New List(Of DataGridColumn)
For Each column As DataGridColumn In boxNoDetail.Columns
    If column.Header <> "Checked" Then
        columnsToRemove.Add(column)
    End If
Next
For Each column As DataGridColumn In columnsToRemove
    boxNoDetail.Columns.Remove(column)
Next
英文:

Since you specify dgv.AutoGenerateColumns = False, the columns will be specified manually which you are doing in:

  1. The XAML: DataGrid.Columns. Here you create the first column, a DataGridCheckBoxColumn.
  2. In dtFillDatagrid where add new columns using your DataGridText function.

You only need to define the columns once. In your current code, you are adding DataGridTextColumns every time dtFillDatagrid executes:

dgv.Columns.Add(myUI.DataGridText(name, name))

You should adjust the code to create the columns once in a separate subroutine when your Window initializes.

If the columns in your DataTable (dt.Columns) potentially change every time you run dtFillDatagrid, then you can remove all the columns except the DataGridCheckBoxColumn (by checking the column's Header value) and then add the new columns like you are doing now. Just add this code to dtFillDatagrid, before adding columns again:

Dim columnsToRemove As New List(Of DataGridColumn)
For Each column As DataGridColumn In boxNoDetail.Columns
    If column.Header &lt;&gt; &quot;Checked&quot; Then
        columnsToRemove.Add(column)
    End If
Next
For Each column As DataGridColumn In columnsToRemove
    boxNoDetail.Columns.Remove(column)
Next

huangapple
  • 本文由 发表于 2023年6月13日 09:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定