Basically I have a datagridview which I retrieve from database and 3 of the database field column I combine into a column in datagridview.
But now the problem come, I need to do update but before that I need to validate what the user have editing before click on the update button, but I don’t know how to validate them when they are in the same column in the datagridview.
I am able to validate a column with only one database field
p.s I am doing editing and updating in the datagridview, I need to validate that 3 database field column.
This is how I call my databasase into the datagridview
ps. the position is 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];
}
this is the column i am saying i am able to validate (only one database field column)
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;
}
}
}
i try this for position , but it give me error: input string was not correct format
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 displaying 3 database fields and allowing the user to edit the same in one column is dangerous. Suggest you to show them as 3 separate columns instead.
Maybe you can also try by making the 3 corresponding properties and merge them via a separator like
|which would not occur in your fields via a fourth property. Now when you get the value split the same on|and perform your checks and also assign back those respective values to the 3 corresponding properties. (But i wouldn’t recommend this)Field1Field2Field3StaffDetails—Field1+”|” +Field2+”|” +Field3Then use e.FormattedValue.ToString() and split this on
|to get string[] of 3 ,now validateAlso you can take a look on creating a Column of
MaskedTextBoxthis will also help but the User experience is gonna be pathetic