【发布时间】:2018-04-04 09:56:18
【问题描述】:
我有一个用于评估的 aspx 页面。该页面的要求之一是创建多个 Gridview 来充当评估表单。 Gridview 由来自我的数据库和文本框的问题以及问题填充。所以 Column1 = 问题 和 Column2 = 文本框。创建的 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);
}
}
【问题讨论】:
-
没有任何创建代码,我只能给你这个提示:“对每个元素使用相同的名称模式,最后增加 ID。所以你可以很容易地收集每个字段(问题/答案),因为你'知道'名字。你可以在 for/while 中循环它并在有
NotFound-Exception时停止它。" -
与使用 FindControl 的 GridView 中的普通文本框相同。正如@LenglBoy 所说,为动态控件提供一个可用于再次找到它的 ID。
-
这是我的问题,我用我的代码更新了我的问题。我不知道如何使用 FindControl 找到它,因为 Gridview 也是动态创建的。