使用动态控件 [英] working with dynamic controls
问题描述
protected void Page_Load(object sender,EventArgs e)
{
for(int i = 0; i< 5; i ++)
{
TextBox textBox = new TextBox();
textBox.ID =c_textBox+ i.ToString();
Button bt = new Button();
template1.Controls.Add(textBox);
bt.Text = i.ToString();
bt.Click + = new EventHandler(Button_Click);
template1.Controls.Add(bt);
}
}
protected void Button_Click(object sender,EventArgs e)
{
/ * wanna在这里* /
}
i相对生成按钮和文本框,并希望将buton的id填入其相关的文本框中,而不会让人感到厌烦其他文本框
如果我按下按钮4,带有id c_textbox的文本框应该是4而不影响其他文本框
请帮助
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TextBox textBox = new TextBox();
textBox.ID = "c_textBox" + i.ToString();
Button bt = new Button();
template1.Controls.Add(textBox);
bt.Text = i.ToString();
bt.Click += new EventHandler(Button_Click);
template1.Controls.Add(bt);
}
}
protected void Button_Click(object sender, EventArgs e)
{
/*wanna do here */
}
i have generated button and textbox relevently and wish to fill the id of buton into its relevent textbox without trigering the other textboxes
like if i press button 4 the textbox with id c_textbox should be 4 without effecting other textboxes
please help
推荐答案
您可以创建一个用户控件(例如UserControl1)带有文本框(例如id TextBox1)和一个Button(例如id Button1)。在用户控件中你可以轻松编写Button_Click事件。
另外,你创建一个公共函数SetValue(int i)来设置Button的Text属性
You can create a usercontrol (e.g. UserControl1) with a Textbox (e.g. id TextBox1) and one Button (e.g. id Button1). In the user control you can easily write Button_Click event.
Also, you create a public function SetValue(int i) to set the Text property of the Button
public void SetValue(int i)
{
Button1.Text = i.ToString();
}
在您的页面中,您可以执行以下操作
In your page, you can do the following
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
UserControl1 uc = new UserControl1();
uc.SetValue(i);
template1.Controls.Add(uc);
}
}
希望有所帮助
Hope it helps
这篇关于使用动态控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!