在DataGridView控件中驗證數據輸入
阿新 • • 發佈:2019-01-01
error src oat png http gevent can datagrid err
實現效果:
知識運用:
DataGridView控件的公共事件CellValidating
//將System.Windows.Forms.DataGridViewCellValidatingEventArgs類的Cancel屬性設為true 將阻止光標離開單元格
和CellEndEdit來處理
實現代碼:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == 0) //驗證指定列 { float result=0; //定義值類型並賦值 if (!(float.TryParse(e.FormattedValue.ToString(), out result))) //判斷是否為數值類型 { dataGridView1.Rows[e.RowIndex].ErrorText = "請輸入數值類型的數據"; //提示錯誤信息 e.Cancel = true; //事件取消的值 } } } private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { dataGridView1.Rows[e.RowIndex].ErrorText = ""; } }
在DataGridView控件中驗證數據輸入