我的 Datagridview 绑定到一个数据表,当用户单击其中一个列标题时,我编写了代码以使用 DefaultView.Sort 方法对我的数据表进行排序,然后我将排序视图设置为我的网格数据源,以下是排序代码:
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
Font f = new System.Drawing.Font("Arial", 8, FontStyle.Bold);
string ColName = dataGridView1.Columns[e.ColumnIndex].Name;
string SortDirection = string.Empty;
foreach (DataRow drforDirection in dtSortDirection.Rows)
{
if (drforDirection["ColumnName"].ToString() == ColName)
{
SortDirection = drforDirection["Direction"].ToString();
drforDirection["Direction"] = (SortDirection == "ASC") ? "DESC" : "ASC";
}
}
tmptotalRow = null;
dtTotals = ((DataTable)dataGridView1.DataSource).Clone();
dtTotals.Rows.Add(((DataTable)dataGridView1.DataSource).Rows[0].ItemArray);
DataTable tmpDataTable = new DataTable();
((DataTable)dataGridView1.DataSource).Rows.RemoveAt(0);
SortDirection = (SortDirection == "ASC") ? "DESC" : "ASC";
((DataTable)dataGridView1.DataSource).DefaultView.Sort = ColName + " " + SortDirection;
tmpDataTable = ((DataTable)dataGridView1.DataSource).DefaultView.ToTable();
tmpDataTable.ImportRow(dtTotals.Rows[0]);
DataRow[] dr = tmpDataTable.Select("ItemLookupCode = 'Grand Totals'");
DataRow newRow = tmpDataTable.NewRow();
// We "clone" the row
newRow.ItemArray = dr[0].ItemArray;
// We remove the old and insert the new
tmpDataTable.Rows.Remove(dr[0]);
tmpDataTable.Rows.InsertAt(newRow, 0);
dataGridView1.DataSource = tmpDataTable;
dataGridView1.Rows[0].Frozen = true;
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.BurlyWood;
dataGridView1.Rows[0].DefaultCellStyle.ForeColor = Color.Black;
dataGridView1.Rows[0].DefaultCellStyle.Font = f;
dataGridView1.Rows[0].ReadOnly = true;
//btnDeleteEmpty_Click(sender, e);
}
我的表单上有一个隐藏空行的按钮,空行是未输入某些列中的数量的行,问题是当用户对网格进行排序时,所有现有的隐藏行都会再次出现。
如何保存行的隐藏属性,以便将其应用于新数据源。