排序的DataGridView的列是文本,而不是价值 [英] Sorting Datagridview's Column by text and not value

查看:120
本文介绍了排序的DataGridView的列是文本,而不是价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我怎样才能做到这一点?

解决方案

您可以通过覆盖在的DataGridView SortCompare 事件做到这一点code>其中:

  

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

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

  1. 电线了 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.

    1. Wire up the SortCompare event to the DataGridView like this:

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

    1. 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.

    这篇关于排序的DataGridView的列是文本,而不是价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆