将GridView中TextBox的值存储到DataBase中?

时间:2012-11-27 11:08:56

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

我有一个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);
    }
}

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

3 个答案:

答案 0 :(得分: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);
}

}

让我知道..

答案 1 :(得分:0)

这句话是错误的 -

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

您无法直接访问子控件的值。这样做 -

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

为了解决您的问题,您应该展示您的Gridview来源以获取帮助。

答案 2 :(得分:0)

它应该是这样的。

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的可见属性是否未设置为 false 。 (当你在按钮点击事件中看到网格视图时。)

此外,我不建议以这种方式插入记录。相反,我会创建一个strored程序&amp;改为传递参数,以避免SQL INJECTION