簡體   English   中英

如何遍歷asp.net gridview的多行並插入數據庫?

[英]How to loop through multiple row of asp.net gridview and insert to the database?

我試圖遍歷所有ASP.Net gridview行,並將它們插入數據庫中。 我為這些操作編寫的代碼如下。 但是問題是將空數據保存到數據庫中。

for (int i = 0; i < GridView1.Rows.Count; i++)
{
     f_name = ((TextBox)GridView1.Rows[i].FindControl("TextBox1"));
     l_name = ((TextBox)GridView1.Rows[i].FindControl("TextBox2"));
     contacts = ((TextBox)GridView1.Rows[i].FindControl("TextBox3"));

     string query = string.Format("insert into [StudentsData].[dbo].[Student_Info] values('{0}','{1}','{2}')",f_name.Text,l_name.Text,contacts.Text);
     command.CommandText = query;

     try
     {
          conn.Open();
          command.ExecuteNonQuery();
     }
     finally
     {
          conn.Close();
     }
}

像這樣進行循環(就像其他一些語句所述,使用帶有參數的存儲過程):

foreach (GridViewRow row in GridView1.Rows)
{
   f_name = ((TextBox)row.FindControl("TextBox1")).Text;
   //etc. 
   using (SqlConnection conn = new SqlConnection(yourConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("yourStoredProcedure", conn))
            {
               cmd.CommandType = System.Data.CommandType.StoredProcedure;
               cmd.Parameters.AddWithValue("@f_name", f_name);
               //etc.
               conn.Open();
               cmd.ExecuteNonQuery();
               conn.Close();
            }
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM