none
Visual Studio 2017 RRS feed

  • Question

  • I want to insert some records in a datagrid-view to a Sql server database.

    In a single record there are 3 columns.

    Data grid view is populated by adding text box values from the windows form.

    I don't want to edit the data back. Just to add those records to the sql server database table.

    Monday, May 20, 2019 5:18 AM

Answers

  • Hi Thushan,

    Thank you for posting here.

    According to your description, you want to insert some records in a datagridview to a sql server database.

    You could refer to the following code.

    private void Button1_Click(object sender, EventArgs e)
            {
                string str = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                SqlConnection sqlConnection = new SqlConnection(str);
                sqlConnection.Open();
                string Sql = String.Format("insert into Student(Name, Age) values('{0}','{1}')", txtName.Text,Convert.ToInt32(txtAge.Text));
                SqlCommand sqlCommand = new SqlCommand(Sql, sqlConnection);
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();
                this.dataGridView1.DataSource = null;
                load();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                load();
            }
    
            private void load()
            {
                string str = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                SqlConnection sqlConnection = new SqlConnection(str);
                sqlConnection.Open();
                string sql = "select *from Student";
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, sqlConnection);
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet);
                this.dataGridView1.DataSource = dataSet.Tables[0].DefaultView;
                sqlConnection.Close();
            }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, May 20, 2019 6:14 AM
    Moderator