【问题标题】:how to sort a DataGridView on edit the coulmn value in winforms using c#如何在使用c#编辑winforms中的列值时对DataGridView进行排序
【发布时间】:2011-12-12 22:50:41
【问题描述】:

我想对数据网格视图进行排序。当用户从此事件 CellValueChanged 对数据网格进行一些更改时。 在 CellValueChanged 完成后,应根据该列对 datagridview 进行排序。我已将数据网格与列表绑定。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您可以使用从DataGridViewCellEventArgssortColumnIndex 属性

        public Form1()
        {
            InitializeComponent();
    
            dataGridView1.CellValueChanged +=new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
    
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("col1"));
            dt.Columns.Add(new DataColumn("col2"));
            dt.Columns.Add(new DataColumn("col3"));
    
            var r1 = dt.NewRow();
            r1["col1"] = "a1";
            r1["col2"] = "b1";
            r1["col3"] = "c1";
    
            var r2 = dt.NewRow();
            r2["col1"] = "a2";
            r2["col2"] = "b2";
            r2["col3"] = "c2";
    
            var r3 = dt.NewRow();
            r3["col1"] = "a3";
            r3["col2"] = "b3";
            r3["col3"] = "c3";
    
            dt.Rows.Add(r1);
            dt.Rows.Add(r2);
            dt.Rows.Add(r3);
    
            BindingSource bs = new BindingSource();
            bs.DataSource = dt;
    
            dataGridView1.DataSource = bs;
    
        }
    
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            var dataGrid = (DataGridView)sender;
            var dataGridColumn = dataGrid.Columns[e.ColumnIndex];
            dataGrid.Sort(dataGridColumn, ListSortDirection.Ascending);
        }
    

    【讨论】:

    • private void datagrid_CellValueChanged(object sender, DataGridViewCellEventArgs e) { ...... ((DataGridView)sender).Sort(((DataGridView)sender).Columns["dgvcOperateur"], ListSortDirection.上升);这段代码给出了错误。你能举一些例子或示例代码吗?用于对 cellvaluechanged 上的数据网格进行排序。
    • DataGridView 控件必须绑定到要排序的 IBindingList 对象。
    • 这是因为您的 DataGridView 正在尝试对集合本身进行排序,这似乎无法排序。你的DataGridView.DataSource是什么类型的?
    • 列表 objSource=新列表(); DataGridView.DataSource=objSource;
    • 列表 objSource=新列表(); DataGridView.DataSource= objSource;得到同样的错误“DataGridView 控件必须绑定到要排序的 IBindingList 对象”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2010-10-26
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多