动态生成的控件,如何获取其ID 或为其传值?

liyingyiwen 2011-03-19 10:47:47
啥不说了 上代码~

//这是第一个动态添加的按钮
Button btnReply = new Button();
btnReply.ID = "btnReply" + Session["MessageID"].ToString();
btnReply.Text = "回应";
btnReply.Visible = true;
btnReply.Click += new EventHandler(btnReply_Click);

protected void btnReply_Click(object sender,EventArgs e)
{
//然后在动态添加的控件的事件里我又动态添加了一个按钮
Button btnNewReply = new Button();
btnNewReply.ID = "btnNewReply" + Session["MessageID"].ToString();
btnNewReply.Text ="******";
btnNewReply.Visible = true;
btnNewReply.Click += new EventHandler(btnNewReply_Click);
}
//新添加的控件的事件
protected void btnNewReply_Click()
{
//现在我想取这个控件的ID
Button btn=(Button)sender;
string id=btn.ID;
//到这里为什么id值为空呢?

}

求教
1:为什么那个id值为空?
2:怎么取btnNewReply控件的ID(我已经为其赋值了啊)?或者是其他相关信息?

附:我查看生成的HTML 果然没有显示btnNewReply的ID....
...全文
378 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
codeMyLife 2011-08-17
  • 打赏
  • 举报
回复

protected void btnNewReply_Click(object sender, EventArgs e)
{
//现在我想取这个控件的ID
Button btn=(Button)sender;//你原先这里的sender是哪里来的
string id=btn.ID;
//到这里为什么id值为空呢?

}


这样?
wjxlove2011 2011-03-20
  • 打赏
  • 举报
回复
学习了!
liyingyiwen 2011-03-19
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wxr0323 的回复:]
C# code
Button b = new Button();
b.ID = "b2";
b.Text = "test";
this.form1.Controls.Add(b);


前台获取代码是。

HTML code
<input type="submit" name="b2" value="te……
[/Quote]


第一个动态添加的按钮确实能得到ID ,HTML里也有呈现 但是后面那个按钮ID却没有!!。。。
就是在动态添加的控件的事件里再定义的控件(好像很繁琐。。)
liyingyiwen 2011-03-19
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 chenshuaijunsfsf 的回复:]
protected void btnReply_Click(object sender,EventArgs e)
{
//然后在动态添加的控件的事件里我又动态添加了一个按钮
Button btnNewReply = new Button();
}
局部变量,应该 定义2个 全局的变量
[/Quote]
能具体说一下吗?定义全局的 Button.text的值是从数据库取出的 必须要在while循环里实时被赋值
全局变量好像不行 全局集合?
sfxdawn 2011-03-19
  • 打赏
  • 举报
回复
對啊,用當前Form.Contorls.Add就可以查看到它的html代碼了
[Quote=引用 3 楼 wxr0323 的回复:]
C# code
Button b = new Button();
b.ID = "b2";
b.Text = "test";
this.form1.Controls.Add(b);


前台获取代码是。

HTML code
<input type="submit" name="b2" value="te……
[/Quote]
deepmist 2011-03-19
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wxr0323 的回复:]
C# code
Button b = new Button();
b.ID = "b2";
b.Text = "test";
this.form1.Controls.Add(b);


前台获取代码是。

HTML code
<input type="submit" name="b2" value="te……
[/Quote]
这个可以
子夜__ 2011-03-19
  • 打赏
  • 举报
回复
 Button b = new Button();
b.ID = "b2";
b.Text = "test";
this.form1.Controls.Add(b);


前台获取代码是。
<input type="submit" name="b2" value="test" id="b2" /></form>
花落_ 2011-03-19
  • 打赏
  • 举报
回复
protected void btnReply_Click(object sender,EventArgs e)
{
//然后在动态添加的控件的事件里我又动态添加了一个按钮
Button btnNewReply = new Button();
}
局部变量,应该 定义2个 全局的变量

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧