C# 排序时丢失DataGridView验证错误。数据源更新完全没有验证
我有一个C# 排序时丢失DataGridView验证错误。数据源更新完全没有验证,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我有一个DataGridView,通过BindingSource绑定到DataTable。简单的示例代码 DataTable records; BindingSource bindRecords; private void InitGrid() { records = new DataTable(); records.Columns.Add(new DataColumn("text", typeof(string))); bindRecords = new Bindi
DataGridView
,通过BindingSource
绑定到DataTable
。简单的示例代码
DataTable records;
BindingSource bindRecords;
private void InitGrid() {
records = new DataTable();
records.Columns.Add(new DataColumn("text", typeof(string)));
bindRecords = new BindingSource();
bindRecords.DataSource = records;
dgvRecords.DataSource = bindRecords;
}
然后我使用CellValidating事件,如下所示:
private void dgvRecords_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
if(e.ColumnIndex == dgvRecords.Columns["text"].Index) {
if(e.FormattedValue.ToString() == "error") {
dgvRecords[e.ColumnIndex, e.RowIndex].ErrorText = "Oops!";
}
}
}
private void btnAddRecord_Click(object sender, EventArgs e) {
records.Rows.Add(new object[] { "error" });
}
现在,当用户以文本形式输入文字“error”时,单元格中会显示一个错误图标。到目前为止还不错
但是如果我对列进行排序,验证将丢失。我理解,为了触发单元验证事件,必须先输入单元,然后再离开单元
以编程方式插入数据时,我也会遇到同样的问题,如下所示:
private void dgvRecords_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
if(e.ColumnIndex == dgvRecords.Columns["text"].Index) {
if(e.FormattedValue.ToString() == "error") {
dgvRecords[e.ColumnIndex, e.RowIndex].ErrorText = "Oops!";
}
}
}
private void btnAddRecord_Click(object sender, EventArgs e) {
records.Rows.Add(new object[] { "error" });
}
我将如何强制进行验证?我不想要像遍历网格和设置CurrentCell这样的黑客行为。您的问题是,
CellValidating
事件似乎只有在您退出单元格(即完成编辑)时才会发生。因此,我测试并发现,将您指定的代码放入另一个排序后触发的事件中(如CellPainting
),可以实现您的愿望。例如:
private void dgvRecords_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == dgvRecords.Columns["text"].Index)
{
if (e.FormattedValue.ToString() == "error")
{
dgvRecords[e.ColumnIndex, e.RowIndex].ErrorText = "Oops!";
}
}
}