【问题标题】:Storing values from TextBox in GridView to DataBase?将GridView中TextBox中的值存储到数据库中?
【发布时间】:2012-11-27 11:08:56
【问题描述】:

我有一个GridView,其中我在每列的项目模板中放置了文本框。我想在单击按钮时将我将在文本框中输入的值存储到数据库中。

protected void Button1_Click(object sender, EventArgs e)
{
    GridView1.Visible = true;
    DataTable dt = new DataTable();
    DataRow row = dt.NewRow();
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        string UserID = GridView1.Rows[i].Cells[1].Text;
        string q="insert into details (name) values('"+UserID+"')";

        SqlCommand cmd = new SqlCommand(q, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
    }
}

问题是当我运行页面时文本框甚至都不可见。

【问题讨论】:

  • 这样不行,搜索“动态添加控件到gridview并检索值”
  • 请出示您的gridview源代码。

标签: c# asp.net sql-server ado.net


【解决方案1】:

您不能直接从网格中获取文本框的引用。 所以首先你需要从每一行网格中找到文本框。 代码应该是这样的。。

protected void Button1_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
DataTable dt = new DataTable();
DataRow row = dt.NewRow();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
   ## add below code ##
    TextBox txtUsrId=(TextBox)GridView1.Rows[i].FindControl("Your textbox id");
    string UserID = txtUsrId.Text;

    string q="insert into details (name) values('"+UserID+"')";

    SqlCommand cmd = new SqlCommand(q, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);
}

}

让我知道..

【讨论】:

    【解决方案2】:

    这个说法是错误的——

     string UserID = GridView1.Rows[i].Cells[1].Text;
    

    您不能直接访问子控件的值。这样做-

    TextBox tt = (TextBox)GridView1.Rows[i].FindControl("your text box");
    string UserId= tt.Text;
    

    说到你的问题,你应该展示你的 Gridview 源以获得帮助。

    【讨论】:

      【解决方案3】:

      应该是这样的。

      protected void Button1_Click(object sender, EventArgs e)
      {
          Int32 TotalRecords = 0;
          SqlConnection con = new SqlConnection("data source=.\; Integrated Security=SSPI; initial catalog=Testdb;User ID=sa;password=abc123;");            
      
          foreach (GridViewRow gvRow in GridView1.Rows)
          {            
              TextBox textBox1 = (TextBox)gvRow.FindControl("textBox1");
      
              String q = "INSERT INTO details ([name]) VALUES('" + textBox1.Text.Trim() + "')";
              SqlCommand cmd = new SqlCommand(q, con);
      
              con.Open();
              TotalRecords += cmd.ExecuteNonQuery();
              con.Close();
          }
      
          lblMessage.Text = "Total " + TotalRecords + " inserted successfully.";
      
      }
      

      关于页面上不显示的文本框,请检查GridView、TemplateField 或TextBox 自身的Visible 属性是否未设置为false。 (当您使 gridview 在按钮单击事件中可见时。)

      我也不建议以这种方式插入记录。相反,我会创建一个存储过程并传递参数,以避免SQL INJECTION

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-30
        • 1970-01-01
        相关资源
        最近更新 更多