排序的DataGridView的列是文本,而不是价值 [英] Sorting Datagridview's Column by text and not value
问题描述
我在我的DataGridView一列,它是一个组合框列。我想它排序它的显示值(即文本),而不是它的值(在这种情况下,廉政局从数据库列表)。
我怎样才能做到这一点?
您可以通过覆盖在的DataGridView 的
SortCompare
事件做到这一点code>其中:
在DataGridView中比较两个单元格的值进行排序操作发生
和对显示值而不是默认值有它总是排序。
- 电线了
SortCompare
事件到DataGridView是这样的:
this.dataGridView1.SortCompare + =新DataGridViewSortCompareEventHandler(dataGridView1_SortCompare);
<醇开始=2>
细胞
的<一个href="https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.formattedvalue.aspx"相对=nofollow> 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
'sFormattedValue
property rather than theValue
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.
这篇关于排序的DataGridView的列是文本,而不是价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!