【问题标题】:DatagridView Column SortingDatagridView 列排序
【发布时间】:2013-05-01 14:01:54
【问题描述】:

我已经使用以下值绑定数据网格。 Id 为 Int,Price 为 int,IsActive 为位。 现在,当我单击 IsActive 的列标题时,我想根据 IsActive 对数据进行排序。

我为 Id 做了同样的事情,它工作正常,但对于 IsActive,它不工作。

下面是我的 IsActive 字段代码:

 private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        // Try to sort based on the cells in the current column.
        e.SortResult = System.String.Compare(e.CellValue1.ToString(), e.CellValue2.ToString());

        // If the cells are equal, sort based on the ID column. 
        if (e.SortResult == 0 && e.Column.Name != "IsActive ")
        {
            e.SortResult = System.String.Compare(
                dataGridView1.Rows[e.RowIndex1].Cells["IsActive "].Value.ToString(),
                dataGridView1.Rows[e.RowIndex2].Cells["IsActive "].Value.ToString());
        }
        e.Handled = true;
    }

我想知道如何在 datagridView 中对布尔数据进行排序。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    根据MSDN -DataGridView.SortCompare Event,只有将“SortMode”属性设置为“Automatic”的列才会触发 SortCompare:

    DataGridViewColumn col = this.dataGridView1.Columns["IsActive"];
    col.SortMode = DataGridViewColumnSortMode.Automatic;
    

    如果可以的话,我会建议让 .Net 做这项肮脏的工作。 假设您的网格视图中有 3 行:

    Id 价格活跃 1 1 1 2 2 1 3 11 1

    在您实现排序的方式中,如果按价格排序,第 3 行将位于第 2 行之前(字符串“11”在“2”之前......)。 最好将数据放在数据表中,将数据表绑定到 gridview,然后让 .Net 完成其余工作:

     /// <summary>
        /// Binds the Grid view.
        /// </summary>
        private void BindGridView()
        {
            //Creating the columns. 
            //The gridview will know how to sort Items by the type specified in the second argment
            DataTable dt = new DataTable();
            dt.Columns.Add("Id",typeof(int));
            dt.Columns.Add("Price",typeof(int));
            dt.Columns.Add("IsActive",typeof(bool));
    
            //Creating some random data
            //Replace this with your actual data...
            Random rnd = new Random(1);
            for (int i = 0; i < 100; i++)
            {
                int Id = i+1;
                int Price = Id%2 == 0? 500-Id*2:350+Id*3;
                bool isActive = (Id%5) !=0;
    
                DataRow row =  dt.NewRow();
                row["Id"] =Id ;
                row["Price"] = rnd.Next(1000) ;
                row["IsActive"] = isActive;
                dt.Rows.Add(row);                
            }
    
            this.dataGridView1.DataSource = dt;
    
            //making sure all columns are sortable
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.Automatic;
            }            
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2012-07-23
      • 2013-07-06
      • 2012-04-06
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多