0

Hello,
I am currently new to C# and am working with a large project. I need to loop through a datagrid, take the user-entered data, and insert it into a database table so I can pull the data from other forms. It is supposed to work when the user clicks the submit button to save all entered info... Not sure if the code I have so far is correct:

private void btnSubmit_Click(object sender, EventArgs e)
        {
            DataTable dtDataTableName = new DataTable("TABLENAME");
            dataGridView.DataSource = dtDataTableName;
            foreach (DataRow dataRow in dtDataTableName.Rows)
            {
                foreach (DataColumn dataColumn in dtDataTableName.Columns)
                {
                    StringBuilder sql = new StringBuilder();
                    sql.Append("Insert into TABLENAME table");
                }
            }

Thanks for any help!:)

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by slavedogg
0

I would replace :

1.
      private void btnSubmit_Click(object sender, EventArgs e)
   2.
      {
   3.
      DataTable dtDataTableName = new DataTable("TABLENAME");
   4.
      dataGridView.DataSource = dtDataTableName;
   5.
      foreach (DataRow dataRow in dtDataTableName.Rows)
   6.
      {
   7.
      foreach (DataColumn dataColumn in dtDataTableName.Columns)
   8.
      {
   9.
      StringBuilder sql = new StringBuilder();
  10.
      sql.Append("Insert into TABLENAME table");
  11.
      }
  12.
      }

with :

private void btnSubmit_Click(object sender, EventArgs e)
        {
            DataTable dtDataTableName = new DataTable("TABLENAME");
            dataGridView.DataSource = dtDataTableName;
            SqlConnection connection = new SqlConnection("Connection string");
            SqlCommand cmd = new SqlCommand("Insert into TABLENAME (Filed1,Filed2) Values (@f1,@f2)",connection);
            cmd.Parameters.AddWithValue("@f1","");
            cmd.Parameters.AddWithValue("@f2","");
            foreach (DataRow dataRow in dtDataTableName.Rows)
            {
                using(connection)
                {
                    connection.Open ();
                    cmd.Parameters[0].Value= dataRow[1].ToString();
                    cmd.Parameters[1].Value= dataRow[2].ToString();
                    cmd.ExecuteNonQuery();
                }
            }
        }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.