有没有办法在动态创建的GridView中获取动态创建的文本框的值? Asp.net

时间:2018-04-04 09:56:18

标签: c# asp.net

我有一个用于评估的aspx页面。该页面的一个要求是创建多个Gridview作为评估表单。 Gridview由我的数据库和文本框中的问题填充。所以 Column1 =问题 Column2 =文本框。创建的Gridviews数量取决于用户在文本框中键入的值。

我的问题是,因为它是动态创建的,所以我不知道如何检索文本框中键入的值。我需要将它们保存在我的数据库中。 我该怎么做?或者有更好的方法吗?

我的代码:

protected void btnOk_Click(object sender, EventArgs e)
{
    btnSave.Visible = true;
    int parCounter = Convert.ToInt32(participants.Text);
    DataTable dt = new DataTable();

    using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
    {
        string sql = "select * from evalForm";

        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                da.Fill(dt);
            }
        }
    }

    for (i = 1; i <= parCounter; i++)
    {
        GridView objGV = new GridView();
        objGV.AutoGenerateColumns = false;
        objGV.ID = "GV"+i;

        for (int col = 0; col < dt.Columns.Count; col++)
        {
            BoundField boundfield = new BoundField();                
            boundfield.DataField = dt.Columns[col].ColumnName.ToString();
            boundfield.HeaderText = dt.Columns[col].ColumnName.ToString();

            objGV.Columns.Add(boundfield);               
        }

        TemplateField tempfield = new TemplateField();
        tempfield.HeaderText = "Score";
        objGV.Columns.Add(tempfield);

        objGV.RowDataBound += new GridViewRowEventHandler(myGrid_RowDataBound);

        compName.Visible = true;
        fromDate.Visible = true;
        toDate.Visible = true;
        participants.Visible = true;

        objGV.DataSource = dt;
        objGV.DataBind();
        Panel1.ContentTemplateContainer.Controls.Add(objGV);
    }        
}

protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
            TextBox txtScore = new TextBox();
            txtScore.ID = "tbScore";
            e.Row.Cells[2].Controls.Add(txtScore);
    }
}

1 个答案:

答案 0 :(得分:1)

要查找任何动态控件,您必须使用FindControl。这也适用于GridView控件。

//loop the dynamic gridviews
for (i = 1; i <= parCounter; i++)
{
    //use findcontrol and cast back to a gridview
    GridView gv = Panel1.ContentTemplateContainer.FindControl("GV" + i);

    //loop all the rows in the gridview
    foreach (GridViewRow row in gv.Rows)
    {
        //use findcontrol again to find the textbox
        TextBox tb = row.FindControl("tbScore") as TextBox;
    }
}