前不久在做一个小家庭管理系统时,用户要求要根据自己想添加的分类自动生成类型控件,便写了一个自定义控件代码:
根据用户选择的类型:自动生成控件
for (int j = 0; j < chType.Items.Count; j++)
{
if (chType.Items[j].Selected)
{
Label lb = new Label();
lb.Text = "支出类型:";
lb.ID = "lbconsanption" + j;
TextBox txtbox = new TextBox();
txtbox.ID = "txtconsanptiontype" + j;
txtbox.Text = chType.Items[j].Text;
txtbox.Width = 60;
TableCell cell = new TableCell();
cell.Controls.Add(lb);
cell.Controls.Add(txtbox);
TableRow row = new TableRow();
row.Cells.Add(cell);
Table tb = new Table();
tb.Rows.Add(row);
Label lb1 = new Label();
lb1.Text = "支出金额:";
TextBox txt2 = new TextBox();
txt2.ID = "txtmouth" + j;
txt2.Width = 60;
txt2.Attributes.Add("onfocabcus", "alert('haha');");
TableCell cell1 = new TableCell();
cell1.Controls.Add(lb1);
cell1.Controls.Add(txt2);
TableRow row1 = new TableRow();
row1.Cells.Add(cell1);
Table tb1 = new Table();
tb1.Rows.Add(row1);
//Button btn = new Button();
//btn.Text = "ok";
//btn.Click += new EventHandler(btn_Click);
//btn.OnClientClick = "return confirm('ok?');";
//PlaceHolder2.Controls.Add(btn);
//PlaceHolder1.Controls.Add(lb);
//PlaceHolder1.Controls.Add(txtbox);
PlaceHolder1.Controls.Add(tb);
PlaceHolder2.Controls.Add(tb1);
}
在将用户填写的值取出 存入数据 库
for (int i = 0; i < chType.Items.Count; i++)
{
if (chType.Items[i].Selected)
{
sp.SpendingType =chType.Items[i].Text;
string mouth = Request.Form["txtmouth" + i];
sp.SpendMouth = mouth;
SpendingTabelManager.Instance.AddSpendingTabel(sp);
}
}