Sunday, October 9, 2011

How to Insert data into Database Tables Using TextBox and Sql Command


In this Tutorial you can easily copy code and learn that how one can insert text data into database table using a Textbox and Button.

Here we are using SQL Server 2005 Express Edition with Visual Studio 2008 and C#.

We have displayed two methods for database connectivity and both are working on button click event and code is in Csharp(C#).

Namespaces:
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Data;  
 using System.Data.Sql;  
 using System.Data.SqlClient;  

Method First:
 protected void Button1_Click(object sender, EventArgs e)  
   {  
 SqlConnection sqlcon = new SqlConnection(@"Data Source =.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True");  
 sqlcon.Open();  
 SqlCommand sqlcmd = new SqlCommand("INSERT INTO Table2(Name) VALUES ('" + TextBox1.Text + "')",sqlcon);  
 sqlcmd.ExecuteNonQuery();  
 sqlcon.Close();  
 }  

Method Second:
 protected void Button1_Click(object sender, EventArgs e)  
   {  
 SqlConnection sqlcon = new SqlConnection(@"Data Source =.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"))  
 SqlCommand CmdSql = new SqlCommand("INSERT INTO [Table1] (Name) VALUES (@Name)", sqlcon);  
 sqlcon.Open();  
 CmdSql.Parameters.AddWithValue("@Name", TextBox1.Text);  
 CmdSql.ExecuteNonQuery();  
 sqlcon.Close();  
     }  

No comments:

Popular Posts