How to save data from datagridview to SQL Server 2008 R2

advertisements

I am creating a C# program where I can add data from the system and save to the the database. I am using SQL Server 2008 R2. I have a data grid view which has 2 tables, name and address. What I want to do is after inputting the needed information I want it to be saved in my database after I click the save button.

This is the screenshot of my data grid view:

I have a code in saving data from a textbox into my database. But I used textbox on that and I don't have any idea on how to do the same process(saving data into my database) using data grid view instead of textbox. Please help. Thanks.

This is the code I used in saving data from a textbox to my database.:

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
    using (SqlConnection connect = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connect;
        command.CommandText = "insert into customer(name, address) values(@name, @address)";
        command.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar));
        command.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar));
        command.Parameters["@name"].Value = name.Text.ToLower();
        command.Parameters["@address"].Value = address.Text.ToLower();
        connect.Open();
    }
}


You need to iterate the DataGridView.Rows collection (I assume the DataGridView is unbounded).

using (SqlConnection connect = new SqlConnection(connectionString))
    {
      using(SqlCommand command = new SqlCommand())
       {
        command.Connection = connect;
        command.CommandText = "insert into customer(name, address) values(@name, @address)";

        command.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar));
        command.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar));
        connect.Open();
        foreach (DataGridViewRow row in dataGridView1.Rows)
         {
          if(!row.IsNewRow)
           {
             command.Parameters["@name"].Value = row.Cells[0].Value;
             command.Parameters["@address"].Value = row.Cells[1].Value;
             command.ExecuteNonQuery();
           }
         }
      }
    }