0

i have a code to move data from asp.net (c# code) to sql. In the following code i have inserted values directly (i.e) xxx and yyy.This works too. Now i want to insert the values which was entered in text boxes. What will be the code to do so?. Help me friends.

protected void Button2_Click(object sender, EventArgs e)
{ 
    string  comm="insert into login values('xxx','yyy')";
    con = new SqlConnection();
    con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString.ToString();
    cmd = new SqlCommand(comm, con);
    cmd.Connection.Open();
    con.Open();
    int i = cmd.ExecuteNonQuery();
    cmd.Connection.Close();  
}
0

1 Answer 1

2
protected void Button2_Click(object sender, EventArgs e) 
{ 
     string  comm="insert into login values(@val1,@val2)";         
    con = new SqlConnection();         
    con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString.ToString();         
    cmd = new SqlCommand(comm, con);         
    cmd.Connection.Open();

    cmd.Parameters.Add("@val1",TextBox1.Text); //Replace TextBox1.Text with your first textbox
    cmd.Parameters.Add("@val2",TextBox2.Text); //Replace TextBox2.Text with your second textbox         

    con.Open();         
    int i = cmd.ExecuteNonQuery();         
    cmd.Connection.Close();      
}
Sign up to request clarification or add additional context in comments.

2 Comments

also, i tried with "insert into login values('" + TextBox1.Text + "','" + TextBox2.Text + "')";
@anvisha Pleasure, please don't use: ('" + TextBox1.Text + "','" + TextBox2.Text + "') as that opens it up to sql injection which isn't good, a quick google will show you why. Please also remember to mark as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.