2012-07-27 100 views
0

我正在使用Windows窗体创建我的第一个C#应用程序,并且我遇到了一些麻烦。我试图验证放置在DataGridView控件的特定单元内的内容。如果内容无效,我想警告用户并用红色突出显示单元格的背景。此外,我想取消该事件,防止用户移动到另一个单元格。当我尝试这样做时,消息框成功显示,但背景颜色从不改变。有谁知道为什么?这里是我的代码:Windows窗体在C#取消事件

 private void dataInventory_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
    { 

     switch (e.ColumnIndex) 
     { 
      case 0: 
       if (!Utilities.validName(e.FormattedValue)) 
       { 
        dataInventory.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red; 
        MessageBox.Show("The value entered is not valid."); 
        e.Cancel = true; 
       } 
       else 
       { 
        dataInventory.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White; 
       } 
       break; 

//更多的东西

回答

0

使用下面的代码

DataGridViewCellStyle CellStyle = new DataGridViewCellStyle(); 
CellStyle.BackColor = Color.Red; 
dataInventory.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle; 
1

消息框不验证过程中使用的最佳工具。通过制作e.Cancel = true;,您告诉网格不要让单元失去焦点,但MessageBox会使光标离开控制。事情有点过时了。

着色部分应该工作,但由于单元格突出显示,您可能没有看到结果。

尝试改变代码使用网格的能力,显示错误图标:

dataGridView1.Rows[e.RowIndex].ErrorText = "Fix this"; 
e.Cancel = true; 

使用CellEndEdit事件来清除消息。

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; 
} 

Walkthrough: Validating Data in the Windows Forms DataGridView Control

+0

这绝对是一个很好的接触,但有没有办法为我改变细胞本身的错误文本,使每个我行可以有单独的错误文本?当我尝试这样做时,使用dataInventory.Rows [(int)row] .Cells [(int)column] .ErrorText =“输入的产品无效。”;系统无法显示错误标志。我认为这与单元格未能突出显示的原因相同:用户正在选择单元格。有避免这个问题的好方法吗? – Nick 2012-07-27 03:56:20

+0

@ user1556487很难回答这个问题。如果你的行标题是可见的,并且按照我的方式设置了错误,那么你会得到一个带有错误文本的工具提示信息的红色圆圈。真正归结为风格。您可以随时在网格旁边的某处显示红色标签,并显示错误消息。 – LarsTech 2012-07-27 12:33:52