DataGridView資料驗證CellValidating()

來源:互聯網
上載者:User
如果是TextBox可以通過KeyPress()事件,讓使用者無法輸入非法資料。
DataGridView中的儲存格,無法通過KeyPress()控制,可能我沒找到方法。
通過CellValidating()在使用者結束編輯時判斷,如果不合法則還原資料。
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    //可編輯的列
    if (e.ColumnIndex != 2 && e.ColumnIndex != 3)
        return;
    double outDb = 0;
    if (double.TryParse(e.FormattedValue.ToString(), out outDb))
    {
        e.Cancel = false;
    }
    else
    {
        e.Cancel = true;//資料格式不正確則還原
        dataGridView1.CancelEdit();
    }
}

TextBox的KeyPress()事件private void txtK_KeyPress(object sender, KeyPressEventArgs e)
{
    double outDb = 0;
    if (double.TryParse(txtK.Text + e.KeyChar.ToString(), out outDb))
    {
        e.Handled = false;
    }
    else
    {
        e.Handled = true;
    }
}

我繼承TextBox重寫KeyPress()封裝了個自訂控制項。
url:http://greatverve.cnblogs.com/archive/2012/06/14/DataGridView-CellValidating.html定義儲存格驗證
要求:
驗證錯誤後焦點不離開。
實現:
儲存格的驗證可以使用dgv_details_CellValidating事件。
驗證不通過時調用e.Cancel = true;終止事件鏈,儲存格將保持編輯狀態。
調用dgv_details.CancelEdit();可以使儲存格的內容會滾到修改前的值。
使用System.Windows.Forms.SendKeys.Send("^a");將全選儲存格的內容。
 
儲存格選中並開始編輯狀態
實現:
//DataGridView獲得焦點
dgv_details.Focus();
//DataGridView指定目前的儲存格
dgv_details.CurrentCell = dgv_details[0, 0];
//開始編輯狀態
dgv_details.BeginEdit(false);
 
定製自動產生綁定了列
實現:
dgv_details.AutoGenerateColumns = false;
 
設定列的背景色
實現:
Color GridReadOnlyColor = Color.LightGoldenrodYellow;
dgv_details.Columns[1].DefaultCellStyle.BackColor =
WinKeys.GridReadOnlyColor;
 
DataGridView儲存格驗證的設計的問題
問題一:綁定還是不綁定?
綁定的優勢:比較簡單,代碼少。
綁定得缺點:DataGridView中的資料受資料來源的影響(主鍵約束、實值型別約束)。不一至時會激發DataError事件,輸入的內容無法儲存到儲存格中和資料來源中。特殊的驗證(比如長度、格式等)還是需要另外寫代碼實現。
關於增加行的問題。增加新行時多主鍵的驗證有問題,而且驗證不通過時會將新行全部刪除。限制很多,很不方便。
 
非綁定的優勢:驗證等處理比較靈活。不受資料來源的約束。
非綁定得缺點:顯示和向資料庫更新資料時需要比較多的代碼實現,效率比較低。
 
總的感覺在處理驗證比較麻煩的場合,我還是比較喜歡非綁定的方式。如果資料量大,驗證比較簡單的場合使用繫結模式比較好 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.