How to insert Data in SQL server via SqlDataSource in ASP.NET





5.00/5 (2 votes)
How to insert Data in SQL server via SqlDataSource in ASP.NET
- First of all, take a new website project.
- Insert two lables, two Textboxes and a Button.
- Rename thier ID like =
lblname
,lblFName
,txtName
,txtFName
andbtnInsert
. - Create database in sqlServer 2005 named
EMPDB
- Create the
Table emp
having 3 fields:ID
= variable typeint
is identity = YESName = varchar(50)
- F
_Name = varachar(50)
- Insert from toolbox->data->sqlDataSource.
- Rename
sqlDataSource
toSqlDS
. - Now double click on button and write the following code:
protected void btnInsert_Click(object sender, EventArgs e) { SqlDS.InsertCommandType = SqlDataSourceCommandType.Text; SqlDS.InsertCommand = "Insert into emp (Name,F_Name) VALUES (@Name, @F_Name)"; SqlDS.InsertParameters.Add("Name", txtName.Text); SqlDS.InsertParameters.Add("F_Name", txtFName.Text); SqlDS.Insert(); txtName.Text = ""; txtFName.Text = ""; }
- Now the record will be inserted to the database.