CEOQAVisual Studio .NET 2003WebFormsVisual Studio 2005.NET 2.0C# 2.0中级开发Visual StudioWindows.NETASP.NETC#
使用 PostBack 解决动态控件问题
创建动态控件并在 PostBack 后将其保留在页面上。
引言
当我尝试在GridView中创建动态控件(例如标签、文本框、复选框等)时,页面回发后会丢失这些控件。我在网上搜索解决方案时没有找到任何相关信息,所以我决定自己解决这个问题。
问题定义
- 首先,我在GridView中添加TemplateColumn
- 然后,我在(ItemTemplate)中放置PlaceHolder控件
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound"
OnDataBinding="GridView1_DataBinding" OnDataBound="GridView1_DataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("RoomID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"
OnPreRender="PlaceHolder1_PreRender"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
然后,在RowDataBound
事件中,根据数据库字段(RoomID
)创建控件的代码如下
protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e) {
PlaceHolder plc = (PlaceHolder)e.Row.Cells[1].FindControl("PlaceHolder1");
Label lbl_RoomID = (Label)e.Row.Cells[0].FindControl("Label1");
Label lblinsert = new Label();
CheckBox chk = new CheckBox();
TextBox txt = new TextBox();
chk.Text = "tttttttt";
lblinsert.Text = "xxxxxxxxx";
if (lbl != null)
{
switch(lbl.Text)
{
case "1":plc.Controls.Add(lblinsert);
arr.Add(lblinsert);break;
case "2":plc.Controls.Add(chk);
arr.Add(chk);break;
case "3": plc.Controls.Add(txt);
arr.Add(txt); break;
default: lblinsert.Text = " Dummy ";
plc.Controls.Add(lblinsert);
arr.Add(lblinsert); break;
}
}
}
}
解决方案
当我在RowDataBound
事件中创建控件时,我将它们添加到ArrayList
中,然后在DataBound
事件中将ArrayList放入Session中
protected void GridView1_DataBound(object sender, EventArgs e)
{
Session.Add("arrcon", arr);
}
然后在PlaceHolder_PreRender
事件中,我获取ArrayList
并在其中重新创建控件,并带上其数据
Int count = 0 ;
protected void PlaceHolder1_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
arr = (ArrayList)Session["arrcon"];
if (arr != null)
{
if (arr[count] is TextBox)
{
TextBox txt = (TextBox)arr[count];
txt.Text = Request.Form[txt.UniqueID].ToString();
((PlaceHolder)this.GridView1.Rows[count].Cells[1].FindControl(
"PlaceHolder1")).Controls.Add(txt);
}
else if (arr[count] is Label)
{
((PlaceHolder)this.GridView1.Rows[count].Cells[1].FindControl(
"PlaceHolder1")).Controls.Add((Control)arr[count]);
}
else if (arr[count] is CheckBox)
{
CheckBox chk = (CheckBox)arr[count];
if (Request.Form[chk.UniqueID] != null)
{
chk.Checked = true;
}
else
{
chk.Checked = false;
}
((PlaceHolder)this.GridView1.Rows[count].Cells[1].FindControl(
"PlaceHolder1")).Controls.Add(chk);
}
count++;
}
}
}
这样就解决了我的问题