首页 新闻 会员 周边 捐助

IComparer实现datagridview中数据的排序问题(紧急)

0
悬赏园豆:20 [已关闭问题] 关闭于 2010-11-02 19:54

 private void button1_Click(object sender, EventArgs e)
        {
            if (RadioButton1.Checked == true)
            {
                DataGridView1.Sort(new RowComparer(SortOrder.Ascending));
            }
            else if (RadioButton2.Checked == true)
            {
                DataGridView1.Sort(new RowComparer(SortOrder.Descending));
            }
        }


        private class RowComparer : System.Collections.IComparer
        {
            private static int sortOrderModifier = 1;

            public RowComparer(SortOrder sortOrder)
            {
                if (sortOrder == SortOrder.Descending)
                {
                    sortOrderModifier = -1;
                }
                else if (sortOrder == SortOrder.Ascending)
                {
                    sortOrderModifier = 1;
                }
            }

            public int Compare(object x, object y)
            {
                DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
                DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;

                // Try to sort based on the Last Name column.
                int CompareResult = System.String.Compare(
                    DataGridViewRow1.Cells[1].Value.ToString(),
                    DataGridViewRow2.Cells[1].Value.ToString());

                // If the Last Names are equal, sort based on the First Name.
                if (CompareResult == 0)
                {
                    CompareResult = System.String.Compare(
                        DataGridViewRow1.Cells[0].Value.ToString(),
                        DataGridViewRow2.Cells[0].Value.ToString());
                }
                return CompareResult * sortOrderModifier;
            }
        }

执行完 DataGridView1.Sort(new RowComparer(SortOrder.Descending));
这句就不再实现public int Compare(object x, object y)
这个方法了。我的datagridview是拖到窗体中的,不像MSdN上是通过代码加法去的。请问哪位前辈能帮着解答下啊!先谢谢了……

柿子贵的主页 柿子贵 | 初学一级 | 园豆:186
提问于:2010-11-01 23:33
< >
分享
所有回答(1)
0

调试看看?!

yoolo wu | 园豆:235 (菜鸟二级) | 2010-11-02 00:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册