Click here to Skip to main content
15,886,806 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
18 Feb 2012CPOL 72.3K   5
How to insert Data in SQL server via SqlDataSource in ASP.NET
  1. First of all, take a new website project.
  2. Insert two lables, two Textboxes and a Button.
  3. Rename thier ID like = lblname,lblFName, txtName, txtFName and btnInsert.
  4. Create database in sqlServer 2005 named EMPDB
  5. Create the Table emp having 3 fields:
    • ID = variable type int is identity = YES
    • Name = varchar(50)
    • F_Name = varachar(50)

  6. Insert from toolbox->data->sqlDataSource.
  7. Rename sqlDataSource to SqlDS.
  8. Now double click on button and write the following code:
    C#
    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 = "";
        }



  9. Now the record will be inserted to the database.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
sigja6-Aug-14 9:58
sigja6-Aug-14 9:58 
Questiongood Pin
kali2rk20-May-13 16:42
kali2rk20-May-13 16:42 
QuestionHello World! Pin
TomkoChoinski12-Jan-13 8:33
TomkoChoinski12-Jan-13 8:33 
AnswerRe: Hello World! Pin
Bjarne Nielsen28-Apr-13 9:01
Bjarne Nielsen28-Apr-13 9:01 
GeneralRe: Hello World! Pin
TomkoChoinski2-May-13 11:57
TomkoChoinski2-May-13 11:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.