This code snippets shows how to Insert NULL value to Date Time Field
Sometime we need to insert null value in DateTime column of the sql server.This code sample is tell you how to achieve that. The language i have used here is C#.
.cs file
//namespaces..
using System.Data.SqlClient;
using System.Data.SqlTypes;
SqlConnection con = new SqlConnection("server=susant\\sqlexpress;Integrated Security=True;Database=Infitech");
protected void Page_Load(object sender, EventArgs e)
{
show();
}
public void show()
{
con.Open();
string str = "select *from user_role";
SqlDataAdapter da = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
//insert..
try
{
string str = "insert into user_role values(@uid,@urole,@dob)";
SqlCommand com = new SqlCommand(str, con);
com.Parameters.Add("@uid", SqlDbType.NChar, 10).Value = TextBox1.Text;
com.Parameters.Add("@urole", SqlDbType.NChar, 10).Value = TextBox2.Text;
if (TextBox3.Text == "")
{
com.Parameters.Add("@dob", SqlDbType.DateTime).Value = SqlDateTime.Null;
}
else
{
com.Parameters.Add("@dob", SqlDbType.DateTime).Value = TextBox3.Text;
}
con.Open();
com.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
show();
}
susant
Banglore