[英]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.