none
C# Insert into SQL when button click RRS feed

  • Question

  • Hi,

    how do i insert data from textbox's in to my SQL database.
    The should do that when some one click linkbutton.

    I have do the
    Code Snippet

    "INSERT INTO [hello] ([hello]) VALUES (@hello)"




    But i don't get how i will do this in codebehind so all the data from the textbox's will be insert into sql database when linkbutton is click.

    Thanks Smile
    Tuesday, May 20, 2008 6:45 PM

Answers

  • Referencing to your original post, you code on linkbutton click event would look like

     

    SqlConnection myConnection = new SqlConnection ("Connection String Here");

    SqlCommand myCommand = new SqlCommand("INSERT INTO [hello] ([hello]) VALUES (@hello)", myConnection);

    SqlParameter helloParam = myCommand.Parameters.Add("@hello", SqlDbType.VarChar );

    helloParam.Value = MyTextBox.Text;

    myConnection.Open();

    myCommand.ExecuteNonQuery();

    Friday, May 23, 2008 5:10 PM
    Moderator

All replies

  • You can do it using
    Tuesday, May 20, 2008 7:31 PM
  • Ok, i have look at that, but i don't get how i should write that in codebehind :&
    Tuesday, May 20, 2008 9:28 PM
  • Why don't you have a look at the example provided at the link I gave you?
    Tuesday, May 20, 2008 9:47 PM
  • I did look at it ;S
    Tuesday, May 20, 2008 9:54 PM
  • private static void InsertUser(string connectionString)
    {
    string SQLInsert = "INSERT INTO [Deltagare] ([fornamn], [efternamn], [alder], [gatuadress], [postort], [mobilP], [mobilM], [alergier], [avdelning], [patrull]) VALUES (@Fornamn, @Efternamn, @Alder, @Gatuadress, @Postort, @Hemtelefon, @MobilP, @MobilM, @Alegier, @Avdelning, @Patrull)";

    using (SqlConnection connection = new SqlConnection(
    connectionString))
    {
    SqlCommand command = new SqlCommand(
    SQLInsert, connection);
    connection.Open();



    }
    }

    So long have i get it, but how do i when i click the button then will insert that?
    Tuesday, May 20, 2008 10:06 PM
  • Just call InsertUser from the button's click event handler, pass the connection string and add all the parameters to the command you are issuing.
    Tuesday, May 20, 2008 10:35 PM
  • The was no InsertUser in the button event's handler, just Page_Load
    • Proposed as answer by NejcZ Monday, December 31, 2012 4:40 PM
    • Unproposed as answer by NejcZ Monday, December 31, 2012 4:40 PM
    Tuesday, May 20, 2008 10:50 PM
  • Referencing to your original post, you code on linkbutton click event would look like

     

    SqlConnection myConnection = new SqlConnection ("Connection String Here");

    SqlCommand myCommand = new SqlCommand("INSERT INTO [hello] ([hello]) VALUES (@hello)", myConnection);

    SqlParameter helloParam = myCommand.Parameters.Add("@hello", SqlDbType.VarChar );

    helloParam.Value = MyTextBox.Text;

    myConnection.Open();

    myCommand.ExecuteNonQuery();

    Friday, May 23, 2008 5:10 PM
    Moderator