【问题标题】:datagrid is sort on edit the cell with binding source list<Student>datagrid 在编辑带有绑定源列表<Student> 的单元格时进行排序
【发布时间】:2011-12-13 08:45:37
【问题描述】:

当用户在事件 dataGridViewStudents_CellValueChanged 中编辑单元格值时。数据网格值相应排序。

 private void form_Load(object sender, EventArgs e)  
        {
            List<student> lststudent=new List<student>(); 
             lststudent.add("1","Abc", 26);
             lststudent.add("1","xyz", 31);
             lststudent.add("1","pqr", 53);
             lststudent.add("1", "def", 23);
            DataGridView.DataSource= lststudent; 
        }
        private void datagridStudent_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[2].Value = 36; ((DataGridView)sender).Sort(((DataGridView)sender).Columns["marks"], ListSortDirection.Ascending);
            }
        }

在此代码中,当用户在数据网格中编辑单元格时。它不会根据该列对数据网格进行排序。数据网格与列表绑定。所以,我想在用户更改单元格值时对数据网格进行排序。

【问题讨论】:

  • 我想你忘记了这个问题:)
  • 在此代码中,当用户在数据网格中编辑单元格时。它不会根据该列对数据网格进行排序。数据网格与列表绑定。所以,我想在用户更改单元格值时对数据网格进行排序。
  • 请参阅 [this][1] 问题。 [1]:stackoverflow.com/questions/1672984/…

标签: c# winforms datagridview


【解决方案1】:
    private void datagridStudent_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        var t = ((List<Student>)DataGridView.DataSource).OrderBy(x=>x.Marks).ToList();
        //or var t =((List<Student>)DataGridView.DataSource).OrderByDescending(x=>x.Marks).ToList();
        DataGridView.DataSource = t;
    }

【讨论】:

  • 最后一行给出错误“操作无效,因为它会导致对 SetCurrentCellAddressCore 函数的可重入调用。”
  • 我应该使用 SortableBindingList 吗?
  • 你可以使用 SortableBindingList。我再次测试代码没有错误。
猜你喜欢
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多