Reputation: 249
when i click on a button it should save the changes i've made to a database, this is the code of the button:
DataRow drow = sql.ds.Tables["Stagiaire"].NewRow();
Boolean allowAdd = false;
if (nom.Text != "" && prenom.Text != "")
allowAdd = true;
if (allowAdd)
{
drow[1] = imgData;
drow[2] = nom.Text.ToUpper();
drow[3] = prenom.Text;
drow[4] = sexe.SelectedItem.ToString();
drow[5] = naiss.Text;
drow[6] = email.Text;
drow[7] = tele.Text;
drow[8] = adresse.Text;
drow[9] = niveau.Text;
drow[10] = filiere.Text;
drow[11] = stage.SelectedItem.ToString();
drow[12] = service.SelectedItem.ToString();
drow[13] = encadrant.SelectedItem.ToString();
drow[14] = etablissement.SelectedItem.ToString();
sql.ds.Tables["Stagiaire"].Rows.Add(drow);
SqlCommandBuilder cmb = new SqlCommandBuilder(daStagiaire);
daStagiaire.Update(sql.ds, "Stagiaire");
XtraMessageBox.Show("Bien Ajouter !");
}
My question is : How can i insert NULL values to the database if the text controllers are empty
Upvotes: 1
Views: 358
Reputation: 6053
u can use dbnull.value
but make sure when you are fetching this null value, add a proper check for null
Upvotes: 0
Reputation: 24488
For each of the fields you need to check if the string contains a value. If it has a value, then pass that value, if it does not have a value, then pass the NULL.
drow[1] = string.IsNullOrWhitespace(imgData)
? (object) imgData : DBNull.Value;
drow[2] = string.IsNullOrWhitespace(nom.Text)
? (object) nom.Text.ToUpper : DBNull.Value;
... do the same logic to the rest of the items.
Here I am using a single line IF THEN statement. Take a look at One-liner if statements, how to convert this if-else-statement for more information.
Upvotes: 1
Reputation: 238126
Pass DBNull.Value
to the database:
drow[11] = string.IsNullOrWhitespace(stage.SelectedItem)
? (object) stage.SelectedItem.ToString()
: DBNull.Value;
Upvotes: 3