我一直在研究一个项目,我将DataTable绑定到DataGridView(2列,双类型)。我想要做的是我想在用户添加新行时以编程方式排序。但问题是,只有当用户填写所有列而不仅仅是一列时,才需要对其进行排序。
即使DataGridViewSortMode设置为NotSortable,当用户添加新行并只填充一列时,它会自动对数据进行排序。
// This is the Form1_Load event.
// Basically populates X, Y, then adds them into DataTable, finally binds it to DataGridView.
private void Form1_Load(object sender, EventArgs e)
{
// Generate X-Y Data
double[] X = new double[]
{ 50, 200, 400, 1000 };
double[] Y = new double[]
{ 150, 300, 50, 250};
// Create DataTable
DataTable dTable = new DataTable();
// Define Column Headers
dTable.Columns.Add("X", typeof(double));
dTable.Columns.Add("Y", typeof(double));
// Add Rows to DataTable
for (int i = 0; i < X.Length; i++)
{
dTable.Rows.Add(X[i], Y[i]);
}
// Bind DataTable to DataGridView
dataGridView1.DataSource = dTable;
}
// This is called when user finishes typing.
// Objective is to determine if all rows are filled.
// IF: all rows have some value --> Sort; IF not --> Do NOT sort data.
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (isNullorEmpty()) // Call a method to see if any row is empty
{
dataGridView1.Columns.Cast<DataGridViewColumn>().ToList().
ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable); // Do not sort because some columns are empty
}
else
{
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending); // Sort data since all columns and rows have value
}
}
当任何行被确定为空时,我刚刚添加了“return”命令,瞧!
这是编辑过的dataGridView1_CellEndEdit事件
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (isNullorEmpty()) // Call a method to see if any row is empty
{
return;
}
else
{
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending); // Sort data since all columns and rows have value
}
}