![](/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.