单元格编辑后无法刷新WPF DataGrid

时间:2022-06-10 22:16:57

I searched several times about datagrid refresh problem. But can't get any idea about it. My problem is as below. Bascially it can work. But if user sort columns and then edit cell, datagrid can't bind. VS would list error "{"Once AddNew or EditItem not allow “Sorting”。"}."

我搜索了几次关于datagrid刷新问题。但无法对此有所了解。我的问题如下。基本上它可以工作。但是如果用户对列进行排序然后编辑单元格,则datagrid无法绑定。 VS会列出错误“{”一旦AddNew或EditItem不允许“排序”。“}。”

But it's friendly for user to be allowed to sort datagrid columns. Please help me to address this problem.Thanks!

但是允许用户对datagrid列进行排序是友好的。请帮我解决这个问题。谢谢!

private void DataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {

           string sql="update table1 set field1='"+cell_value+''
            BindGR();

        }


   private void BindGR()

    {
        //Bind DataGrid
        if (dt != null)
        {
            DataGrid1.ItemsSource = dt.DefaultView;

        }

    }

1 个解决方案

#1


0  

View.xaml

View.xaml

 <DataGrid x:Name="MyDataGrid" 
             Sorting="DataGrid_OnSorting" 
             ItemsSource="{Binding DataGridItems, Mode="TwoWay"}">
 </DataGrid>

View.xaml.cs

View.xaml.cs

    private ObservableCollection<DataClass> dataGridItems = new ObservableCollection<DataClass>();

    public ObservableCollection<DataClass> DataGridItems
    {
        get { return dataGridItems; }
        set { SetProperty(ref dataGridItems, value); }
    }

Please try with TwoWay binding ie Mode="TwoWay" for Itemssource

请尝试使用TwoWay绑定,即Modessource的Mode =“TwoWay”

If it doesn't work, try code below. I did not test the code, since it is not fully implemented. Try to get an idea from this!

如果它不起作用,请尝试下面的代码。我没有测试代码,因为它没有完全实现。试着从中得到一个想法!

private void DataGrid_OnSorting(object sender, DataGridSortingEventArgs e)
{
    var sortedGrid = sender as DataGrid;
    foreach (var item in sortedGrid.Items)
    {
        DataGridItems.Add(item);
    }
}

#1


0  

View.xaml

View.xaml

 <DataGrid x:Name="MyDataGrid" 
             Sorting="DataGrid_OnSorting" 
             ItemsSource="{Binding DataGridItems, Mode="TwoWay"}">
 </DataGrid>

View.xaml.cs

View.xaml.cs

    private ObservableCollection<DataClass> dataGridItems = new ObservableCollection<DataClass>();

    public ObservableCollection<DataClass> DataGridItems
    {
        get { return dataGridItems; }
        set { SetProperty(ref dataGridItems, value); }
    }

Please try with TwoWay binding ie Mode="TwoWay" for Itemssource

请尝试使用TwoWay绑定,即Modessource的Mode =“TwoWay”

If it doesn't work, try code below. I did not test the code, since it is not fully implemented. Try to get an idea from this!

如果它不起作用,请尝试下面的代码。我没有测试代码,因为它没有完全实现。试着从中得到一个想法!

private void DataGrid_OnSorting(object sender, DataGridSortingEventArgs e)
{
    var sortedGrid = sender as DataGrid;
    foreach (var item in sortedGrid.Items)
    {
        DataGridItems.Add(item);
    }
}