c#如何改变动态生成的按钮的属性

2025-01-25 12:31:59
推荐回答(1个)
回答1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Drawing;

namespace formaaa
{
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

ViewState["DataFieldCount1"] = 0;
ViewState["DataFieldCount2"] = 0;
}
else
{
for (int counter = 0; counter < (int)ViewState["DataFieldCount1"]; counter++)
{
AddBtn1();
}
for (int counter = 0; counter < (int)ViewState["DataFieldCount2"]; counter++)
{
AddBtn2();
}
}
}

private void AddBtn1()
{
Button bt = new Button();
//bt.Text=((int)ViewState["DataFieldCount1"]+1).ToString();
PlaceHolder1.Controls.Add(bt);

int btnLast=setBtn1ID();

((Button)PlaceHolder1.Controls[btnLast-1]).Text = btnLast.ToString();
((Button)PlaceHolder1.Controls[btnLast - 1]).Click += new EventHandler(btnAddtn2_Click);
}
private void AddBtn2()
{
Button bt = new Button();
//bt.Text=((int)ViewState["DataFieldCount1"]+1).ToString();
PlaceHolder2.Controls.Add(bt);

int btnLast = setBtn2ID();
((Button)PlaceHolder2.Controls[btnLast - 1]).Click += new EventHandler(btnBtn2_Click);

}

protected void btnAddButton_Click(object sender, EventArgs e)
{
ViewState["DataFieldCount1"] = (int)ViewState["DataFieldCount1"] + 1;
AddBtn1();
}

protected void btnAddtn2_Click(object sender, EventArgs e)
{
ViewState["DataFieldCount2"] = (int)ViewState["DataFieldCount2"] + 1;
AddBtn2();
((Button)PlaceHolder2.Controls[PlaceHolder2.Controls.Count - 1]).Text = ((Button)sender).Text;

}
private int setBtn1ID()
{
int i = 1;
//将用户控件与其按钮设置为相同的ID
foreach (Button bt in PlaceHolder1.Controls )
{
bt.Text = i.ToString();
bt.ID = i.ToString();

i++;
}
i=i-1;
return i;

}
private int setBtn2ID()
{
int i = 1;
//将用户控件与其按钮设置为相同的ID
foreach (Button bt in PlaceHolder2.Controls)
{

bt.ID = "b"+i.ToString();

i++;
}
i = i - 1;
return i;

}

protected void btnBtn2_Click(object sender, EventArgs e)
{

foreach (Button bt in PlaceHolder1.Controls)
{
if (bt.Text == ((Button)sender).Text)
{
bt.BackColor = Color.Red;

}
}

}

}

}
试试这个时间有限,没有来得及写说明,如果需要再联系
在页面中放一个button 其id为btnAddButton
再放两个PlaceHolder其id分别为PlaceHolder1和PlaceHolder2就可以了