i have a windows application form and i want to insert the text box values into sql database, some of them are mandatory others are allowed to insert null values. But i cant insert null values(in the case of int) into database.
CREATE TABLE [dbo].[tblReg](
[Reg_ID] [int] IDENTITY(1,1) NOT NULL,
[Sep_Status] [varchar](50) NOT NULL,
[Pop_Grp] [varchar](50) NOT NULL,
[Child_Address] [varchar](50) NULL,
[Child_AgeYr] [int] NULL
) ON [PRIMARY]
These are my c# code
private void Children_Save_Click(object sender, EventArgs e)
{
ss = SepStat.Text.ToString().Trim();
pg = PopGr.Text.ToString().Trim();
Add = ChildAdd.Text.ToString().Trim();
yr = Convert.ToInt32(ChildDOBYr.Text);
createdid=SaveChilDetails(ss,pg,Add,yr);
}
public int SaveChilDetails(string ss, string pg,string Add,int yr)
{
string constring =Config.GetConnection();
using (SqlConnection con=new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("Insert into tblReg(Sep_Status,Pop_Grp,Child_Address,Child_AgeYr) output INSERTED.Reg_ID values(@ss,@pg,@Add,@yr)", con))
{
cmd.Parameters.AddWithValue("@ss", ss);
cmd.Parameters.AddWithValue("@pg", pg);
if (Add == "") //Problems are here
{ cmd.Parameters.AddWithValue("@add", null); }
else
{ cmd.Parameters.AddWithValue("@Add", Add); }
if(yr==0)
{cmd.Parameters.AddWithValue("@yr", null);}
else
{cmd.Parameters.AddWithValue("@yr", yr);} //***********************
if (con.State != ConnectionState.Open)
con.Open();
int createid = (int)cmd.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open) con.Close();
return createid;
}
}
}