![](/img/trans.png)
[英]Get values of Dynamically Created Controls inside Asp.Net Gridview C#
[英]Is there a way to get the values of Dynamically created Textbox inside a Dynamically created GridView? Asp.net
我有一个aspx页面用于评估。 该页面的要求之一是创建多个Gridview以用作评估表。 Gridview由数据库和文本框中的问题以及问题组成。 所以Column1 = Questions和Column2 = Textbox 。 创建的Gridview的数量取决于用户在文本框中键入的值。
我的问题是,由于它是动态创建的,所以我不知道该如何检索文本框中键入的值。 我需要将它们保存在我的数据库中。 我应该怎么做? 还是有更好的方法呢?
我的代码:
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);
}
}
要查找任何动态控件,您必须使用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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.