繁体   English   中英

在C#,Gridview,Winforms中的数据网格中交换行

[英]interchanging rows in a datagrid in C#,Gridview,Winforms

我在C#.net中做一个winforms应用程序,我在网格视图中有一组数据(根据文本框条目填充。如果我在文本框中输入ID,则其在网格视图中的对应数据如下所示:

        A  B    C     D 
       100 1   30500  null
       100 1   23000  null
       100 1   50000  null
       100 2   23000  null
       100 2   31300  null
       100 2   50000  null

在上面的数据中,C列中的值50000具有2个子项,每个子项分别对应于B列中的值(B中的30500,23000->值1和B列中的23000,31300->值2)。 我希望看到以下表格:

          A  B    C     D 
       100 1   50000  null
       100 1   30500  null
       100 1   23000  null
       100 2   50000  null
       100 2   23000  null
       100 2   31300  null

I would like to have the row corresponding to the value 50000( highest) to appear first to show that the below 2 entries (beneath each 50000) are its sub items.
     I do not know how to do that since I am a beginner in c# Winforms.     
     Appreciate any help. Thanks in advance.

您必须对用于datagridView的数据源进行排序。 我假设数据表是您的数据源。 您必须对B列进行一次升序排序,然后对C列进行降序两次排序。

如果dataTable1是您的数据源,则类似下面的内容,您需要做..

DataView view = new DataView(dataTable1);
view.Sort = "B ASC, C DESC";
DataTable newTable = view.ToTable();

然后使用NewTable作为您的数据源。

另一种方法是从数据库端通过在当前查询的末尾添加ORDER BY B ASC和C DESC来进行处理。

如果您有数据表作为数据源,则kishore VM的答案将起作用,这是另一种有效的方法,无论数据源如何。

在DataGrid SortCompare上注册并自己处理排序比较。

    dgv.SortCompare += new DataGridViewSortCompareEventHandler(OnDataGridViewSortCompare);

    void OnDataGridViewSortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        int retVal = String.Compare(e.CellValue1.ToString(), e.CellValue2.ToString());
        //They are ==, Compare by next column
        if (retVal == 0)
        {
            retVal = String.Compare(dgv[e.Column.Index + 1, e.RowIndex1].Value.ToString(),
            dgv[e.Column.Index + 1, e.RowIndex2].Value.ToString()) * -1; //Multiply by -1 to flip the ASC sort to DESC
        }
        e.SortResult = retVal;
        e.Handled = true;
    }

我不确定是否要存储字符串或整数值,所以我使用了字符串比较。 如果要进行真正的数字比较,则需要将单元格值转换/解析为int并使用自己的int compare方法,因为int没有内置的字符串或十进制值。

    void OnDataGridViewSortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        int retVal = CompareInt((int)e.CellValue1, (int)e.CellValue2);
        //They are ==, Compare by next column
        if (retVal == 0)
        {
            retVal = CompareInt((int)dgv[e.Column.Index + 1, e.RowIndex1].Value,
                (int)dgv[e.Column.Index + 1, e.RowIndex2].Value) * -1; //Multiply by -1 to flip the ASC sort to DESC
        }
        e.SortResult = retVal;
        e.Handled = true;
    }

    int CompareInt(int value1, int value2)
    {
        if (value1 == value2) return 0;
        else if (value1 < value2) return -1;
        else return 1;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM