2012-07-27 98 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