Code
1 private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
2 {
3 if (e.Button == MouseButtons.Left)
4 {
5 String columnName = this.dataGridView1.Columns[e.ColumnIndex].Name;
6 SortOrder so = this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection;
7
8 if (so == SortOrder.Ascending)
9 {
10 columnName = columnName + " asc";
11
12
13 }
14 else if (so == SortOrder.Descending)
15 {
16 columnName = columnName + " desc";
17
18 }
19
20 DataTable dt1 = dt.Copy();
21
22 DataRow[] drs = dt1.Select(String.Empty, columnName);
23
24 dt.Clear();
25 foreach (DataRow dr in drs)
26 {
27 dt.ImportRow(dr);
28 }
29
30 this.dataGridView1.DataSource = dt;
31 }
32 }
33
1 private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
2 {
3 if (e.Button == MouseButtons.Left)
4 {
5 String columnName = this.dataGridView1.Columns[e.ColumnIndex].Name;
6 SortOrder so = this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection;
7
8 if (so == SortOrder.Ascending)
9 {
10 columnName = columnName + " asc";
11
12
13 }
14 else if (so == SortOrder.Descending)
15 {
16 columnName = columnName + " desc";
17
18 }
19
20 DataTable dt1 = dt.Copy();
21
22 DataRow[] drs = dt1.Select(String.Empty, columnName);
23
24 dt.Clear();
25 foreach (DataRow dr in drs)
26 {
27 dt.ImportRow(dr);
28 }
29
30 this.dataGridView1.DataSource = dt;
31 }
32 }
33
2.sorted事件排序方法,以前也研究过sorted事件,可是一直都找不到答案,觉得没什么用,特别是事件参数为EventArgs,一点信息都提不出来。 最近看到同事的代码,觉得不错。不过改代码有个问题,就是如果在sorted中重新绑定DataGridView, 则多次单击列标题时标题会没反应,代码如下:
Code
private void dataGridView1_Sorted(object sender, EventArgs e)
{
string _sortStr = this.dataGridView1.SortedColumn.Name; //排序列
//排序方向
SortOrder _so = this.dataGridView1.SortOrder;
if (_so == SortOrder.Ascending)
{
_sortStr += " asc";
}
else
{
_sortStr += " desc";
}
DataView _dv = this.dtTemp.DefaultView;
_dv.Sort = _sortStr; //排序
this.dtTemp = _dv.ToTable(); //将排序后的datatable赋给 this.dtTemp
}
private void dataGridView1_Sorted(object sender, EventArgs e)
{
string _sortStr = this.dataGridView1.SortedColumn.Name; //排序列
//排序方向
SortOrder _so = this.dataGridView1.SortOrder;
if (_so == SortOrder.Ascending)
{
_sortStr += " asc";
}
else
{
_sortStr += " desc";
}
DataView _dv = this.dtTemp.DefaultView;
_dv.Sort = _sortStr; //排序
this.dtTemp = _dv.ToTable(); //将排序后的datatable赋给 this.dtTemp
}