[英]How to validate a datagridview column with 3 database field combine together
基本上我有一個從數據庫中檢索的datagridview,我將3個數據庫字段列組合成datagridview中的一個列。
但是現在問題來了,我需要進行更新,但在此之前我需要在單擊更新按鈕之前驗證用戶編輯的內容,但是當它們位於 datagridview 的同一列中時,我不知道如何驗證它們.
我能夠驗證只有一個數據庫字段的列
ps我正在datagridview中進行編輯和更新,我需要驗證3個數據庫字段列。
這就是我將我的數據庫調用到 datagridview 中的方式
附言。 position 是 int
protected void BindStaff()
{
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=BRandCom;Integrated Security=True");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT StaffID, (StaffName+','+ StaffNRIC+','+ Position + ';')as StaffDetail, yearIn, age, address, email, stayIndicator FROM StaffBook", conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
DGVStaffBook.DataSource = ds.Tables[0];
}
這是我說我能夠驗證的列(只有一個數據庫字段列)
private void DGVStaffBook_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
int stayInd;
if (e.ColumnIndex == 6)
{
stayInd = Convert.ToInt32(DGVStaffBook.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
if (stayInd != 0 && stayInd != 1)
{
MessageBox.Show("Please enter only 1 or 0");
DGVStaffBook.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = DBNull.Value;
}
else
return;
}
}
}
我為 position 嘗試這個,但它給了我錯誤:輸入字符串格式不正確
private void DGVStaffBook_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
if (e.ColumnIndex == 1)
{
String[] position = null;
position = Convert.ToString(DGVStaffBook.CurrentRow.Cells[1].Value).Split(',');
if (int.Parse(position[2]) != 1 && int.Parse(position[2])!=2 )
{
MessageBox.Show("Please Update number type accordingly:" + Environment.NewLine + "1 - High rank only " + Environment.NewLine + "2 -Low Rank" );
}
else
return;
}
}
}
IMO 顯示 3 個數據庫字段並允許用戶在一列中編輯相同的字段是危險的。 建議您將它們顯示為 3 個單獨的列。
也許您也可以嘗試制作 3 個相應的屬性並通過分隔符合並它們,例如|
這不會通過第四個屬性出現在您的字段中。 現在,當您在|
上獲得相同的值拆分時並執行您的檢查,並將這些各自的值分配回 3 個相應的屬性。 (但我不推薦這個) Field1
Field2
Field3
StaffDetails
-- Field1
1 +“|” + Field2
2 +“|” + Field3
然后使用 e.FormattedValue.ToString() 並將其拆分為|
得到 3 的字符串 [],現在驗證
你也可以看看創建一個MaskedTextBox
列,這也會有所幫助,但用戶體驗會很糟糕
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.