How Do I Get a Dynamic Control's Value after Postback? - c#

I have a listview that adds controls in the ItemDataBound Event. When the postback occurs, I cannot find the new controls. After a bit of research, I found that ASP .NET needs these controls created every time, even after postback. From there I moved the function to bind the ListView outside of the if (!Page.IsPostBack) conditional. Now I get the dynamic controls values but the static controls I have are set to their defaults. Here is a sample of what I am trying to accomplish:
For brevity, I left some obvious things out of this example.
<asp:ListView runat="server" ID="MyList" OnItemDataBound="MyList_ItemDataBound">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</LayoutTemplate>
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="ProductPlaceHolder">
<asp:TextBox runat="server" ID="StaticField" Text="DefaultText" />
<asp:PlaceHolder ID="DynamicItems" runat="server" />
</asp:PlaceHolder>
</ItemTemplate>
</asp:ListView>
and here is the codebehind:
protected void MyList_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e) {
PlaceHolder DynamicItems = (PlaceHolder)e.Item.FindControl("DynamicItems");
DynamicItems.Controls.Add(textbox);
}
So, like I said, if I only databind when Page != PostBack then I cant find my dynamic controls on postback. If I bind every time the page loads then my static fields get set to their default text.

Try moving the data binding of the ListView into the OnInit() event.

Very similar question (instead of populating a ListView the guy is generating a set of buttons). Briefly, you'll find that you have to store the items in the list in your Viestate - than fish it out on Postback and re-populate the list.
Note that this solutions implies dropping data-binding (which you might not wanna do for others reasons).
Hope it helps.

Related

How to avoid post-back of Check Box inside repeater

I am newbie for asp.net,
I have a repeater which contains check box,whenever I check the check box I am firing an event on checkchanged,but the page postbacks.
I have an update panel for the entire content in my page,but still postback occurs.Is there anyway to avoid postback.
(Ps:To avoid Postback,I am meaning to avoid the flicker that occurs)
Thanks
<asp:Repeater ID="rptrDepartment" runat="server" OnItemCommand="rptrDepartment_ItemCommand"
OnItemDataBound="rptrdepartment_databound">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID ="chkRow" runat="server" OnCheckedChanged="ChkRow_ChkChanged" AutoPostback="true" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
And in my .cs page,
protected void ChkRow_ChkChanged(object sender, EventArgs e)
{
//some method
}
Just keep your repeater inside update panel rather than entire page, if you want some other controls also need partial postback then you can go for multiple update panels.

Create a Repeater control in ASP.Net

I'm using two drop down and bind values to that drop down.
Now am adding a new button add_new.
I want to create the above drop downs below when I click the add button and maintain the previous selected values. Please help me to do this.
You can achieve the desired result using Repeater control of ASP.Net. You can create any type of template as you wish, see the code below:
ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" />
<asp:DropDownList ID="DropDownList2" runat="server" />
<br />
</ItemTemplate>
</asp:Repeater>
CodeBehind:
protected void Button1_Click(object sender, EventArgs e)
{
// data fetching logic
Repeater1.DataSource = data;
Repeater1.DataBind();
}
Hard to answer without a better explanation and code samples but from experience doing anything with dropdowns over postbacks is better controlled with hidden fields. Set the value of the hidden field with javascript. Please provide more detail.

ASP.NET ListView control not firing OnItemCommand Event

I know that this sounds like a number of other posts, all of which I have read but have not addressed my issue.
Here's the Scenario ...
I have BOTH a Repeater and a ListView bound to the same Data Source. Each control contains an ASP:LinkButton which, when clicked, should fire the OnItemCommand event. Although they are wired to the EXACT same data at the EXACT same places in the page life cycle and View State is enabled for the page and each individual control the Repeater appears to fire the event and the ListView does not.
I know that the event will not fire if the data is not bound BEFORE the assignment of the event handler. I am relying on ViewState to repopulate the controls when the page is posted back to. Looking at each control in debug mode while stepping through a request I can see that the Repeater DOES indeed appear to repopulated with the ViewState data but the ListView does not.
As these are both generated, populated, bound, and handled almost IDENTICALLY I am at a complete loss why this may be happening. I have also noticed a similar issue with the GridView control (it does NOT fire the event). I assume that these are related somehow.
The only thing that I can think of that the GridView and ListView have in common that the Repeater does not is the built-in paging capability. Whether implemented or not is there something with the paging that affects the loading of the ViewState?
OrderControl.ASCX is a control which exposes the ListView and Repeater as properties (OrderListLV & OrderListRPT) to the host page/application.
<asp:ListView runat="server" id="lvOrderList" OnItemDataBound="lstOrderList_OnItemDataBound" EnableViewState="true" >
<LayoutTemplate>
<table class="tblGrid">
<tr runat="server" id="itemPlaceholder" />
</table>
<ASP:DataPager runat="server" ID="dataPager1" PageSize="3">
<Fields>
<ASP:NextPreviousPagerField
ButtonType="Button"
ShowFirstPageButton="true"
ShowLastPageButton="true"
ShowNextPageButton="true"
ShowPreviousPageButton="true" />
</Fields>
</ASP:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr class="row-">
<td align="center"><ASP:LinkButton runat="server" id="lnkOrderId1" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Repeater runat="server" id="rptOrderList" OnItemDataBound="rptOrderList_ItemDataBound">
<HeaderTemplate>
<table class="tblGrid">
</HeaderTemplate>
<ItemTemplate>
<tr">
<td align="center"><ASP:LinkButton runat="server" id="lnkOrderId" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
OrderControl.ASCX.CS is where the controls are bound to the data source in the Pre-Render stage, well after ViewState has had the opportunity to reconstitute itself.
protected override void OnPreRender(EventArgs e)
{
this.lstOrderList.DataSource = this.OrderHeaders.OrderByDescending(x => x.OrderDate).ToList();
this.lstOrderList.DataBind();
this.rptOrderList.DataSource = this.OrderHeaders.OrderByDescending(x => x.OrderDate).ToList();
this.rptOrderList.DataBind();
}
Host.ASPX.CS is the page which consumes the control. It attaches the event handlers directly the controls in it's OnLoad handler.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.OrderControl.OrderListRPT.ItemCommand += new RepeaterCommandEventHandler(OrderList2_ItemCommand);
this.OrderControl.OrderListLV.ItemCommand += new EventHandler<ListViewCommandEventArgs>(OrderList_ItemCommand);
}
After all is said and done when I click on the LinkButton in each control the ItemCommand Handler for the Repeater fires and executes correctly but the process doesn't even enter the handler for the ListView handler.
I am crazy confused on this issue. I am hoping that someone might have some thoughts on this. Something I can try at least?
Thanks,
Gary
you should set the CommandName property of each LinkButton in the ListView, eventually also the CommandArgument.
<td align="center">
<asp:LinkButton runat="server" id="lnkOrderId1" CommandName="yourCommandName" CommandArgument="yourCommandArgument" />
</td>
also check asked questions here in SO before posting a new question ;-)
listview OnItemCommand dosen't fire up

How can I trigger UpdatePanel from Event within a dynamically loaded UserControl?

I am writing a card game app using Ajax, c# and .NET 3.5. Due to the nature of the interface I have numerous update panels that Im trying to manage and update across various user action. I'm having problems with one though.
The players current hand is built by binding a list of Card objects to a repeater and then dynamically creating a Card UserControl and adding it to the Controls of a PlaceHolder when each item is databound. The code is roughly as follows:
On the page
<asp:UpdatePanel ID="pnlInHand" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="rptInHand" runat="server" onitemdatabound="rptInHand_ItemDataBound">
<ItemTemplate>
<asp:PlaceHolder ID="plcInHandCard" runat="server" />
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
In code behind
protected void rptInHand_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Card card = (Card)e.Item.DataItem;
PlaceHolder plcCard = (PlaceHolder)e.Item.FindControl("plcInHandCard");
plcCard.Controls.Add(CreateCardControl());
}
private CardControl CreateCardControl()
{
CardControl cardControl = (CardControl)Page.LoadControl("~/UserControls/CardControl.ascx");
//Set control properties here
return cardControl;
}
The Card Control includes a Button. The ClickEvent for this button calls a Method of the Parent Page that needs to update a seperate UpdatePanel as well as remove the card Control from the Panel that it is sitting within.
I have two issues.
When I click the Card Control Button, because it has been created as part of a repeater within an updatePanel, it no longer exists when the page is posted back and so the Click event for the button within the control never fires. I can obviously rebind the repeater on page load, but does this mean I have to essentially do this on every postback?
More importantly I need a way to trigger the update of another updatepanel in the parent page when the Card control's click event is raised. Is there a way of setting a trigger on an update panel that listens out for an event within a dynamicaly loaded UserControl?
Many thanks
Stewart
Sample code from ASP.net site that should address your point 2 problem follows.
I'll leave the translation to your code to you.
I may be misunderstanding what you are trying to do but I believe once you get this working your issue with point 2 is no longer relevant as you'll get the AJAX postback you want from your parent update panel.
Good luck!
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="itemDataBound">
<ItemTemplate>
<mycontrol:user ID="user1" runat="server" OnCausePostBack="user1_CausePostBack" /> <br />
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
protected void itemDataBound(object sender, RepeaterItemEventArgs e)
{
ModalPopup_WebUserControl mw=(ModalPopup_WebUserControl)e.Item.FindControl("user1");
AsyncPostBackTrigger at = new AsyncPostBackTrigger();
at.ControlID = mw.ID;
at.EventName = "CausePostBack";
UpdatePanel2.Triggers.Add(at);
}
protected void user1_CausePostBack(object sender, EventArgs e)
{
// do something
}
just an idea for point 2 : what about add a property in the cardControl to set a reference to the updatepanel/s ? from there you can add triggers or call panel.update in the button event
for point one yes u will have to do it. u will have to re create the controls
for point 2 a simple updatePanel.update() would do the job insode of any event if you are using an event that was binded to a dynamically created control then u will have to rebind the event on every page postback

AJAX Update Panel - Action button click on drop down selection

Evening all
I have the following scenarion. I have a range of drop down menus where a clietn can select. The code below is wrapped in an update panel but without this, the button click fires a method to retrieve the number of products. So for example, an item is selected from ddlCategory, the btnValidate is clicked and the label returns the number of products within that category.
I have the following code for an update panel - I'm just not sure how to implement if effectively.
<asp:UpdatePanel ID="UpdatePanel1" runat="Server">
<ContentTemplate>
<asp:Label ID="lblSearchResultsStatus" runat="server" Text="Number of results found: "></asp:Label>
<asp:Label ID="lblSearchResults1" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate Search"
OnClick="btnValidate_Click" Width="120px" />
</ContentTemplate>
</asp:UpdatePanel>
How do I go about wiring the update panel so that when a drop down list item is selected, the buttong is effectively clicked?
Do I have to implement something on each of the ddlSelectedIndexChanged event or is there a property within the update panel that does?
Apologies for the noob question.
The point of the UpdatePanel is to update a portion of the page with an AsyncPostBack instead of reloading the whole page, but in order for the drop-down lists to trigger an AsyncPostBack automatically, they must be on an UpdatePanel. In order to update the labels, they must be on the same UpdatePanel with the labels.
A common pattern to implement what you want to accomplish:
Put the DDLs on the UpdatePanel, and set AutoPostBack="true" on each DDL, so they trigger AsyncPostBacks.
Add an event handler for SelectedIndexChanged on each DDL (can be the same event handler).
Move whatever you do in btnValidate_Click to another method.
Call the new method from btnValidate_Click and the SelectedIndexChanged event handler(s) so they all perform the same function.
You can call your btnValidate_Click event from codebehind at any point, i.e. Page_Load
protected void Page_Load(object sender, EventArgs e)
{
btnValidate_Click(btnValidate, new EventArgs());
}

Categories