FindControl无法获取动态生成的控件的解决办法
本帖最后由 xyytcs 于 2013-07-05 21:11:16 编辑 请问各位大侠有没有FindControl无法获取动态生成的控件的解决办法啊?
说明:
1. 数据库没问题,读取数据也没问题,就是要根据id获取动态生成的控件来进行相应操作。但是现在就是无法获取,一直都是空,id都是没问题的。
2. 已经百度了好久,查找了好些资料,只希望有碰到过此问题的大侠们帮忙,如有能帮忙解决问题者,分可以加倍,不是自己的经验粘贴别人的,就请不要打扰了。 控件
[解决办法]
1、FindControl方法针对后台数据绑定控件的,如果是动态生成的获取不了。
2、你可以看一看生成的客户端代码,在前台用Jquery取取看。
[解决办法]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
<p> 我是一个动态生成的textbox奥!我的行id是<%#Eval("key") %></p>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="submitBtn" runat="server" Text="我是提交按钮奥" OnClick="submitBtn_Click" />
</form>
</body>
</html>
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Dictionary<string, string> testdic = new Dictionary<string, string>();
testdic.Add("1", "1");
testdic.Add("2", "2");
testdic.Add("3", "3");
testdic.Add("4", "4");
rpt1.DataSource = testdic;
rpt1.DataBind();
//下面动态创建textbox添加到repeater里面去
for (int i = 0; i < rpt1.Items.Count; i++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "creatbox_" + i.ToString();
txtBox.Text = "creatbox_" + i.ToString();
rpt1.Items[i].Controls.Add(txtBox);
}
}
}
protected void submitBtn_Click(object sender, EventArgs e)
{
//尝试读取动态控件的值
for (int i = 0; i < rpt1.Items.Count; i++)
{
string curVal = Request.Form["rpt1$ctl" + i.ToString("00") + "$creatbox_" + i.ToString()] + "";
TextBox txtBox = new TextBox();
txtBox.ID = "creatbox_" + i.ToString();
txtBox.Text = curVal;
rpt1.Items[i].Controls.Add(txtBox);
}
}
}