使用Windows应用程序刷新endit事件中的datagrid

时间:2011-12-15 10:49:18

标签: c# winforms c#-4.0 datagridview

  1. 在表单加载时绑定数据网格。

    DataGrid1.DataSource = objBindinglist
    
  2. 更改了datagrid中的值

    DataGrid1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
       DataGridViewCell cell = null;
    
       if (e.RowIndex > -1 && e.ColumnIndex > -1)
       {
         cell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex];
        ((DataGridView)sender).Rows[e.RowIndex].Cells[sates.Index].Value = cell;
       }
    }
    
  3. 编辑后我想刷新数据网格。

    private void DataGrid1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
      ((DataGridView)sender).DataSource = null;
      var lstDataSource = 
        ((BindingList<person>)(((DataGridView)sender).DataSource))
        .OrderByDescending(x => x.sates).ToList();
    objBindinglist = new BindingList<person>(lstDataSource);
    DataGrid1.DataSource = objBindinglist;
    
  4. 一个绑定列表在顶部声明。

     BindingList<person> objBindinglist = new BindingList<person>();
    
  5. 问题:  是否可以将刷新列表绑定到有界数据网格。  当我在endit事件中给datasource为null时,它会给出错误。

1 个答案:

答案 0 :(得分:0)

我认为你很难在EndEdit事件中更改DataSource,因为网格很可能仍然需要这些数据。

如果您的目标是简单地使用数据,那么使用内置排序机制会更好。配置网格时,在SortColumn属性中设置要对数据进行排序的列,并将SortOrder属性设置为System.Windows.Forms.SortOrder.Descending

如果编辑完成后网格未正确更新,只需调用Sort方法。