how to take data from Textbox and add into the database

1.    First of all you have to add two textbox and one button in a form.  After that you have to create add             namespace using System.Data.SqlClient .
2.     Goto project then click into Add Components and then click on Service-based Database.
3.    In Server Explorer you have to create a table by clicking Tables .


In this example i am creating a table of two column one is s_no and other is name.
After that you have to add these code into Button_Click...



private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\yogesh\Documents\Visual Studio 2008\Projects\sq_1\sq_1\yoyo.mdf;Integrated Security=True;User Instance=True");
            sc.Open();
            SqlCommand sd = new SqlCommand("insert into student(s_no,name) values(@s_no,@name)", sc);
            sd.Parameters.AddWithValue("@s_no", textBox1.Text);
            sd.Parameters.AddWithValue("@name", textBox2.Text);
            sd.ExecuteNonQuery();
            sc.Close();
        }

To see data in a table you have to do change the path in a SqlConnection, for this you have to click  app.config file
in a solution explorer.
In a app.config file you have to copy the path form    Data Source  upto  User Instance=true.
To see data you have to click server explorer  then click tables than  right click on table name ( ie students in my case)  then Show table Data........
I hope you like this code




Ebook Download
View all
Learn
View all