Reputation: 17
I am trying to insert empty text box value into database by stored procedure.But i do not know how to pass null values through stored procedure please help me. My Class is
public Void empqualadd(string id, string name, string qual1)
{
SqlCommand cmd = new SqlCommand("InsertQual");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MachID", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@EmpCode", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("@Qualification1", SqlDbType.VarChar).Value = qual1;
conn.nonquery(cmd);
}
My Button Click is,
protected void Button1_Click(object sender, EventArgs e)
{
mas.empqualadd(ddis.SelectedItem.Text,
txtfname.Text,ddqual.SelectedItem.Text);
}
I have a connection clas too,
public Connection()
{
conn = new SqlConnection(@"server=SIGNET- SOFTWARE\SA;database=manjilas;Integrated security=true");
cmd = null;
}
public void nonquery(SqlCommand cmd)//for insert,delete,update
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
It works fine for insert data if text box is not empty.What changes I should made in class to pass null values? Please Help me.Thanks in advance....
Upvotes: 0
Views: 658
Reputation: 17
This also works fine.
if(!string.IsNullOrWhiteSpace(qual2)&!string.IsNullOrWhiteSpace(clg2)&!string.IsNullOrWhiteSpace(mark2)&!string.IsNullOrWhiteSpace(year2))
{
cmd.Parameters.Add("@Qualification2", SqlDbType.VarChar).Value = qual2.Length > 0 ? qual2 : (object)DBNull.Value;
cmd.Parameters.Add("@College2", SqlDbType.VarChar).Value = clg2.Length > 0 ? clg2 : (object)DBNull.Value;
cmd.Parameters.Add("@Mark2", SqlDbType.Int).Value = mark2.Length > 0 ? mark2 : (object)DBNull.Value;
cmd.Parameters.Add("@Year2", SqlDbType.VarChar).Value =year2.Length > 0 ? year2 : (object)DBNull.Value;
conn.nonquery(cmd);
}
Upvotes: 0
Reputation: 10694
Try this
cmd.Parameters.Add("@MachID", SqlDbType.Int).Value = string.IsNullOrEmpty(id) ? (object)DbNull.Value : id;
Also why are you passing string value when column data type is int?
Upvotes: 3