Saturday, March 10, 2012

User control in UpdatePanel

I wrote some testing codes and found the similar?issues?as?yours.If?you?want?to?access?user?control?in?asp:UpdatePanel, you?can?take?a?look?at?the?following?codes.Maybe?this?is?not?good?to?program,but?it?can?do?what?you?need?indeed.
User Controls:
<%@. Control Language="C#" AutoEventWireup="true" CodeFile="UCListBox.ascx.cs" Inherits="Web_User_Controls_UCListBox" %>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
<asp:ListItem Text="Microsoft" Value="0"></asp:ListItem>
<asp:ListItem Text="IBM" Value="1"></asp:ListItem>
<asp:ListItem Text="HP" Value="2"></asp:ListItem>
<asp:ListItem Text="BP" Value="3"></asp:ListItem>
</asp:ListBox>
Behind Codes:
public partial class Web_User_Controls_UCListBox : System.Web.UI.UserControl
{
private static string _selectedText = string.Empty;
public static string SelectedText
{
get
{
return _selectedText;
}
}

protected void Page_Load(object sender, EventArgs e)
{

}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
_selectedText = ListBox1.SelectedItem.Text;
}
}
Web Form refering the User Control:
<div>
<asp:UpdatePanel ID="UpdateListBox" runat="server">
<ContentTemplate>
Selected Text:<asp:Label ID="lblSelectedText" runat="server"></asp:Label>
<hr />
<uc1:UCListBox ID="UCListBox1" runat="server" />
<asp:Button ID="btnGetSelectedText" runat="server" Text="Get Selected Text" OnClick="btnGetSelectedText_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnGetSelectedText" />
</Triggers>
</asp:UpdatePanel>
</div
protected void btnGetSelectedText_Click(object sender, EventArgs e)
{
Label lbl = UpdateListBox.FindControl("lblSelectedText") as Label;
lbl.Text = Web_User_Controls_UCListBox.SelectedText;
}
Wish the above sample codes can give you some ideas.
Found the solution myself. You need to register the user control as a (async) postback trigger:

<Triggers><asp:AsyncPostBackTriggerControlID="UserControl1"/></Triggers>This works, because apparently, "You can also reference to a naming container as a trigger. In this case, all child controls in the container that cause postback will be considered as triggers for theUpdatePanel." (seehttp://ajax.asp.net/docs/mref/1df78e90-f402-5c08-08ae-b75fc1ea22d5.aspx)

No comments:

Post a Comment