winform手动绑定数据后,点击列标题不能实现自动排序,苦苦寻找方法,发现下面的是可行的。
//建立DataTable将当前dataGridView中的数据读进DataTable中 public DataTable dvtodt(DataGridView dv) { DataTable dt = new DataTable(); DataColumn dc; for (int i = 0; i < dv.Columns.Count; i++) { dc = new DataColumn(); dc.ColumnName = dv.Columns[i].HeaderText.ToString(); dt.Columns.Add(dc); } for (int j = 0; j < dv.Rows.Count; j++) { DataRow dr = dt.NewRow(); for (int x = 0; x < dv.Columns.Count; x++) { dr[x] = dv.Rows[j].Cells[x].Value; } dt.Rows.Add(dr); } return dt; } 调用方法: private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { //取得点击列的索引 int nColumnIndex = e.ColumnIndex; DataTable d = dvtodt(dataGridView1); if (SortOrder_ == 0) //程序開始定義 private int SortOrder_=0; { d.DefaultView.Sort = this.dataGridView1.Columns[nColumnIndex].Name + " ASC"; //指定升序排列 SortOrder_ = 1; } else { d.DefaultView.Sort = this.dataGridView1.Columns[nColumnIndex].Name + " desc"; //再次點擊變爲降序排列 SortOrder_ = 0; } dataGridView1.Columns.Clear(); dataGridView1.DataSource = d; }
已实现双向排序