簡體   English   中英

Windows窗體中的C#取消事件

[英]Windows Forms in C# cancel event

我正在使用Windows窗體創建我的第一個C#應用程序,但遇到了一些麻煩。 我正在嘗試驗證放置在DataGridView控件的特定單元格內的內容。 如果內容無效,我想警告用戶並以紅色突出顯示單元格的背景。 此外,我想取消該事件以防止用戶移動到另一個單元格。 當我嘗試執行此操作時,將成功顯示該消息框,但背景顏色永遠不會改變。 有人知道為什么嗎? 這是我的代碼:

        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;

//更多東西

MessageBox不是在驗證期間使用的最佳工具。 通過使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;
}

請參閱演練:在Windows Forms DataGridView控件中驗證數據

使用以下代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM