0

我已经使用以下值绑定数据网格。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 中对布尔数据进行排序。

4

1 回答 1

1

根据MSDN -DataGridView.SortCompare Event,SortCompare 将仅针对其“SortMode”属性设置为“Automatic”的列触发:

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;
        }            


    }
于 2013-04-30T05:17:06.083 回答