<asp:Button id='btnAdd' style='Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 168px'
runat='server' Text='Add Record'></asp:Button>
<asp:TextBox id='txtFirstName' style='Z-INDEX: 102; LEFT: 168px; POSITION: absolute; TOP: 40px'
runat='server'></asp:TextBox>
<asp:TextBox id='txtLastName' style='Z-INDEX: 103; LEFT: 168px; POSITION: absolute; TOP: 80px'
runat='server'></asp:TextBox>
<asp:TextBox id='txtDate' style='Z-INDEX: 104; LEFT: 168px; POSITION: absolute; TOP: 120px' runat='server'></asp:TextBox>
<asp:Label id='Label1' style='Z-INDEX: 105; LEFT: 56px; POSITION: absolute; TOP: 240px' runat='server'></asp:Label>
On Page_Load
VB.NET
if not Page.IsPostBack then
’....
end if
C#
if(!Page.IsPostBack )
{
//...
}
Use namespaces System.Data.SqlClient, System.Data.SqlTypes
On Button Click
VB.NET
Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = 'insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) '
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;'
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)
cmd.Parameters.Add(New SqlParameter('@FirstName', SqlDbType.NVarChar, 11))
cmd.Parameters.Add(New SqlParameter('@LastName', SqlDbType.NVarChar, 40))
cmd.Parameters.Add(New SqlParameter('@Date', SqlDbType.DateTime))
sqldatenull = SqlDateTime.Null
cmd.Parameters('@FirstName').Value = txtFirstName.Text
cmd.Parameters('@LastName').Value = txtLastName.Text
If (txtDate.Text = '') Then
cmd.Parameters('@Date').Value = sqldatenull
’cmd.Parameters('@Date').Value = DBNull.Value
Else
cmd.Parameters('@Date').Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = 'Record Inserted Succesfully'
Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try
On Button Click
C#
string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlCommand cmd =null;
SqlDateTime sqldatenull ;
try
{
sqlStmt = 'insert into Employees (FirstName,LastName,HireDate) Values (@FirstName,@LastName,@Date) ';
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;';
cn = new SqlConnection(conString);
cmd = new SqlCommand(sqlStmt, cn);
cmd.Parameters.Add(new SqlParameter('@FirstName', SqlDbType.NVarChar, 11));
cmd.Parameters.Add(new SqlParameter('@LastName', SqlDbType.NVarChar, 40));
cmd.Parameters.Add(new SqlParameter('@Date', SqlDbType.DateTime));
sqldatenull = SqlDateTime.Null;
cmd.Parameters['@FirstName'].Value = txtFirstName.Text;
cmd.Parameters['@LastName'].Value = txtLastName.Text;
if (txtDate.Text == '')
{
cmd.Parameters ['@Date'].Value =sqldatenull ;
//cmd.Parameters['@Date'].Value = DBNull.Value;
}
else
{
cmd.Parameters['@Date'].Value = DateTime.Parse(txtDate.Text);
}
cn.Open();
cmd.ExecuteNonQuery();
Label1.Text = 'Record Inserted Succesfully';
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
cn.Close();
}
Share with