排序的DataGridView的列是文本,而不是价值而不是、文本、价值、DataGridView

2023-09-04 00:09:34 作者:我赐你万劫不复死而无墓

我在我的DataGridView一列,它是一个组合框列。我想它排序它的显示值(即文本),而不是它的值(在这种情况下,廉政局从数据库列表)。

我怎样才能做到这一点?

解决方案

您可以通过覆盖在的DataGridView 其中:

  

在DataGridView中比较两个单元格的值进行排序操作发生

为什么在我电脑里面打开的ftp出现的内容不是平铺排列而是竖着排列的,而且,还不能上传作业

和对显示值而不是默认值有它总是排序。

电线了 SortCompare 事件到DataGridView是这样的:

this.dataGridView1.SortCompare + =新DataGridViewSortCompareEventHandler(dataGridView1_SortCompare);

然后添加事件处理程序由各所有列的 细胞 FormattedValue的 属性,而不是的 财产(这是默认值)。

无效dataGridView1_SortCompare(对象发件人,DataGridViewSortCompareEventArgs E) {     VAR DGV =(DataGridView中)发件人     字符串值1 = dgv.Rows [e.RowIndex1] .Cells [e.Column.Index] .FormattedValue.ToString();     字符串值2 = dgv.Rows [e.RowIndex2] .Cells [e.Column.Index] .FormattedValue.ToString();     e.SortResult = System.String.Compare(值1,值2);     e.Handled =真实; }

我的作品,并希望能帮助其他人出来。我只希望有对的DataGridView 设置使这个默认的选项。

I have a column in my datagridview that is a combobox column. I would like it sorted by it's display value (i.e. text) instead of it's value (in this case, a list of int's from the database).

How can I do this?

解决方案

You can do this by overriding the SortCompare event on the DataGridView which:

Occurs when the DataGridView compares two cell values to perform a sort operation

and having it always sort on the Display Value instead of the Default Value.

Wire up the SortCompare event to the DataGridView like this:

this.dataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(dataGridView1_SortCompare);

Then add the event handler to sort all columns by each Cell's FormattedValue property rather than the Value property (which is the default).

void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    var dgv = (DataGridView) sender
    string value1 = dgv.Rows[e.RowIndex1].Cells[e.Column.Index].FormattedValue.ToString();
    string value2 = dgv.Rows[e.RowIndex2].Cells[e.Column.Index].FormattedValue.ToString();

    e.SortResult = System.String.Compare(value1, value2);
    e.Handled = true;
}

Works for me, and will hopefully help other people out. I just wish there was a setting on the DataGridView to make this the default option.

 
精彩推荐
图片推荐