說明:動態產生控制項TextBox、CalendarExtender與DropDownList並取值,其中產生控制項最好放在事件OnInit裡,可透過ViewState來更新控制項的屬性值。本例已有一列靜態控制項,並搭配HiddenField來紀錄資料列數。
語法:
//code behind
using AjaxControlToolkit;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int iNum = 0;
if (!string.IsNullOrEmpty(hidNum.Value))
iNum = int.Parse(hidNum.Value);
AddRecord(iNum, false);
}
}
protected void btnMore_Click(object sender, EventArgs e)
{
int iNum = 0;
if (!string.IsNullOrEmpty(hidNum.Value))
iNum = int.Parse(hidNum.Value);
iNum++;
hidNum.Value = iNum.ToString();
AddRecord(int.Parse(hidInvoiceNum.Value), true);
}
private void AddRecord(int iNum, bool blFlag)
{
int iTemp = 1;
if (blFlag) iTemp = iNum;
for (int i=iTemp; i <= iNum; i++)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TextBox txtNo = new TextBox();
txt.ID = "txtNo" + i;
tc1.Controls.Add(txtNo);
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
TextBox txtDate = new TextBox();
CalendarExtender ce = new CalendarExtender();
txtDate.ID = "txtDate" + i;
ce.TargetControlID = "txtDate" + i;
ce.Format = "yyyy/MM/dd";
this.PlaceHolder1.Controls.Add(ce);
tc2.Controls.Add(txtDate);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
DropDownList ddlType = new DropDownList();
ddlType.ID = "ddlType" + i;
ddlType.DataSource = datasource;
ddlType.DataTextField = "Text";
ddlType.DataValueField = "Value";
ddlType.DataBind();
tc3.Controls.Add(ddlType);
tr.Cells.Add(tc3);
//Add Server Control Table
this.tbTest.Rows.Add(tr);
}
//取值
for (int i = 0; i <= int.Parse(hidNum.Value); i++)
{
txtNo = (TextBox)tbTest.FindControl("txtNo" + i);
txtDate = (TextBox)tbTest.FindControl("txtDate" + i);
ddlType = (DropDownList)tbTest.FindControl("ddlType" + i);
}
沒有留言:
張貼留言