Dropdown list selected index changed - asp.net

I did my drop down list that get its values from the database and when running the application, it did not work and the compiler did not see the code.
// aspx
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDlProductFamily" runat="server"
ondatabound="DDlProductFamily_DataBound"
onselectedindexchanged="DDlProductFamily_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DDlProductFamily" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
// cs
protected void DDlProductFamily_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("SelectThumbByProductFamily", Con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#ProductCategory_Id",
DDlProductFamily.SelectedValue.ToString()));
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
}

Check if listbox has property AutoPostBack="True".

You need to be loading the DLL data on, for example, Page Load, it is empty so your DDL will never have its SelectedIndex changed.
You need to do something like this psuedo code:
Page_load
{
if(!IsPostBack)
{
BindData();
}
}
BindData()
{
// Do your DataBase/whatever call to fill the DDL
}
And your code for protected void DDlProductFamily_SelectedIndexChanged(object sender, EventArgs e) stays the same.
Your DDL will also need the property AutoPostBack="true"

Do you have AutoEventWireup="true" set in the page directive at the top of your ASPX page? You will need this setting set to true in order for your code to work.
For more information please see Information about the AutoEventWireup attribute:
In Visual Studio .NET or in Visual
Studio 2005, events are bound to
event-handler methods using event
delegates. If you use the Web Forms
Designer to design Web Forms, the
designer automatically generates code
to bind events to their event-handler
methods.

Related

Updatepanel in ascx refreshing the whole control

I've got a sitecore proejct, in which I have prepared a sub-layout in the form of an ascx User Control. I need to set up cascading drop downs in this user control, and based on what I found an UpdatePanel is the way to go. The problem is that the UpdatePanel seems to be refreshing the whole control, which I don't think is the correct behaviour.
I understand there are some similar questions on SO, but none of the solutions worked for me. I'm also beginning to suspect that this may be a Sitecore specific issue.
Here is a code sample of the user control:
<p><%= MyItem.Text %>" /></p>
<asp:UpdatePanel ID="LocationFilterUpdatePanel" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDL1" OnSelectedIndexChanged="DDL1_SelectedIndexChanged" runat="server" AutoPostBack="true">
</asp:DropDownList>
<asp:DropDownList ID="DDL2" OnSelectedIndexChanged="DDL2_SelectedIndexChanged" runat="server" AutoPostBack="true">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
And the Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!System.Web.UI.ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
var context = new SitecoreContext();
//Get Model from Sitecore
DDL1.DataSource = Model.Data;
DDL1.DataValueField = "Id";
DDL1.DataTextField = "Name";
DDL1.DataBind();
}
}
protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
var context = new SitecoreContext();
//Get Model from Sitecore
DDL2.DataSource = Model.Data;
DDL2.DataValueField = "Id";
DDL2.DataTextField = "Name";
DDL2.DataBind();
}
protected void DDL2_SelectedIndexChanged(object sender, EventArgs e)
{
}
The page loads fine, but (when debugging) changing the DDL1's index it will show a Null exception in MyItem.Text. This is outside the control panel. Note: I have also added a script manager.
There are plenty of things I've tried. Setting different update modes, updated the AjaxToolkit in my solution by executing Install-Package AjaxControlToolkit from the Package Manager Console... but the behaviour remains the same.
Thank you.
Put the databinding for DDL1 to the OnInit, rather than the Page_Load.
And don't include the if statement in there, just do the databind.
After the OnInit the selected values will be correctly set and you will be able to access the DDL1's options in the other event handlers.
You have asp:DropDownList control with an AutoPostBack set to true.
Remove the AutoPostBack=true from the Dropdownlist control and set an Async trigger for your UpdatePanel, set to the Dropdownlist and its eventname="SelectedIndexChanged"
This is a know issue, and you find a lot of documentation about it.

Literal Control text rendering doesn't work in Update Panel

In my ASP.NET app I have Update Panel and Custom server control in it.
This Custom control has inside Literal Control. I try to set it's text property programmatically. But it doesn't render, because Literal Control is in Update Panel.
How can I solve this? Thanks very much.
Here is my code:
<asp:UpdatePanel runat="server" ID="updPanel">
<ContentTemplate>
<st:AspGridViewTitlePanel runat="server" ID="GridTitle" Width="100%">
</st:AspGridViewTitlePanel>
</ContentTemplate>
</asp:UpdatePanel>
AspGridViewTitlePanel - it's my server control. It has such code:
this.myLiteralControl = new LiteralControl();
this.myLiteralControl.Text = "Some text";
protected void page_load(object sender, args e) {
if (!Page.IsPostBack) {
LiteralControl myLiteralControl = new LiteralControl();
myLiteralControl.Text = #"<span> MY TEXT </span>";
UP1.ContentTemplate.Controls.Add(myLiteralControl);
}
}
Adding controls dynamically to an UpdatePanel in ASP.NET AJAX

UpdatePanel does not work when AjaxControlToolkit lib is included

I work on a simple ASP Webform project (asp framework 4.0), and use VS 2010.
I have a some pages on my website where I want to use UpdatePanels.
On another page of my website, i need to use ModalPopupExtender control wich is included in the AjaxControlToolkit lib.
The problem that i encountered is that my UpdatePanels do not work at all if I include the AjaxControlToolkit library in my project (no need to implement any component of this library, just adding a reference to it in my project).
If I remove the reference to the lib, it works fine.
Do you have an idea on how to concile those both elements ? UpdatePanel and AjaxControlToolkit lib ?
Thanks a lot for your advice
Here is the simple UpdatePanel code I use:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="show" CommandName="show"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="label1"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Repeater1" EventName="ItemCommand" />
</Triggers>
</asp:UpdatePanel>
In code behind, I use this :
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = new List<String>(){"zero", "un", "deux", "trois","quatre"};
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
LinkButton lnk = ((LinkButton)e.Item.FindControl("lnk"));
lnk.CommandArgument = e.Item.ItemIndex.ToString();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "show")
label1.Text = "You click" + e.CommandArgument;
}
I found this post because i was the same problem when added a reference for AjaxToolKit.dll,
then was looking what could be the problem then found this with the comment to see the javascript errors and was the solution :D
I had in my code a script to get the start of the refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
var elementID = sender._activeElement.id;
...
}
was getting "TypeError: sender._activeElement is undefined"
then changed the
var elementID = sender._activeElement.id;
to
var elementID = sender._postBackSettings.sourceElement.id;
and solved my problem.
Without the reference to the dll was working fine and when I remove it.
With the reference I had to change the properties of the element.

ASP.Net GridView UpdatePanel Paging Gives Error On Second Click

I'm trying to implement a GridView with paging inside a UpdatePanel. Everything works great when I do my first click. The paging kicks in and the next set of data is loaded quickly. However, when I then try to click a link for another page of data, I get the following error:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 12030
aspx code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="2"
AllowPaging="true" AllowSorting="true" PageSize="20"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_PageSorting"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ActivityLogID" HeaderText="Activity Log ID" SortExpression="ActivityLogID" />
<asp:BoundField DataField="ActivityDate" HeaderText="Activity Date" SortExpression="ActivityDate" />
<asp:BoundField DataField="ntUserID" HeaderText="NTUserID" SortExpression="ntUserID" />
<asp:BoundField DataField="ActivityStatus" HeaderText="Activity Status" SortExpression="ActivityStatus" />
</Columns>
</asp:GridView>
</contenttemplate>
</asp:UpdatePanel>
code behind
private void bindGridView(string sortExp, string sortDir)
{
SqlCommand mySqlCommand = new SqlCommand(sSQL, mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
mySqlAdapter.Fill(dtDataTable);
DataView myDataView = new DataView();
myDataView = dt.DefaultView;
if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
GridView1.DataSource = myDataView;
GridView1.DataBind();
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
protected void GridView1_PageSorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
}
any clues on what is causing the error on the second click?
If anything on your page that is outside UpdatePanel, is changing after the first click, or try to change, on second click is comething diferent, but your calls did get again the fist one value because there are outside UpdatePanel and did not get the update value, just get the first one again -> So product an error on second click.
Probably you have out side the UpdatePanel some data thats need to be rendered correctly.
Keep inside UpdatePanel anything that you change and use with this control.
For example the sSQL, where do you store it ? Its change ? Maybe other value changes on click ?
Probably you have out side the UpdatePanel some data thats need to be rendered correctly. Keep inside UpdatePanel anything that you change and use with this control.

UpdatePanel where Button Event does not fire

I have a UpdatePanel with a PlaceHold contained in it. I create some controls with Labels and Buttons, when Button is clicked it fires an Event that clears PlaceHolder and adds some Textboxes and a Button with an Event.
Problem is when this Button is click it appears to do a PostBack and does not fire Event associated with Button. I thought that since these controls are all contained within the UpdatePanel the would be no PostBack, am I missing the flow.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<%--<%# Register assembly="System.Web.DynamicData, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.DynamicData" tagprefix="cc1" %>
--%>
<div id="content" > <!--start content div-->
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:UpdatePanel ID="upBlog" runat="server" UpdateMode="Conditional">
<ContentTemplate >
<asp:PlaceHolder ID="phBlog" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers >
<%-- <asp:AsyncPostBackTrigger EventName="Click" ControlID = "btnSave" />--%>
</Triggers>
</asp:UpdatePanel>
<br />
</div> <!--ends content div-->
</asp:Content>
//Code Behind
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
FirstView();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void FirstView()
{
FileStream fs = new FileStream(Server.MapPath(GlobalVar.compathver), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
DataSet dset = new DataSet();
dset.ReadXml(fs);
fs.Close();
//other controls
Button btnComments = new Button();
btnComments.ID = "mybtnComments" + i.ToString();
btnComments.BorderWidth = 0;
btnComments.Text = MyFunc.CountComments(row["ID"].ToString(), dset) + " Comments";
phBlog.Controls.Add(btnComments);
btnComments.CommandArgument = row["ID"].ToString();
btnComments.BorderWidth = 0;
btnComments.Command += new CommandEventHandler(Button1_Click)
}
private void CommentView(string ID) /// THIS DOES not FIRE
{
DataView myCommentView = GetCommentView(ID);
Button btnCommentSave = new Button();
btnCommentSave.ID = "mySavebtnComments" + i.ToString();
btnCommentSave.Text = "Publish";
btnCommentSave.BackColor = Color.Aquamarine;
phBlog.Controls.Add(btnCommentSave);
btnCommentSave.CommandArgument = row["ID"].ToString();
btnCommentSave.Click += new EventHandler(btnSave_Click);
}
protected void Button1_Click(object sender, CommandEventArgs e)
{
CommentView(e.CommandArgument.ToString());
}
protected void btnSave_Click(object sender, EventArgs e)
//protected void btnSave_Click(object sender, CommandEventArgs e)
{
FileStream fsxml = new FileStream(Server.MapPath(GlobalVar.compathver), FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
//other code
// XML Document Saved
xmldoc.Save(fsxml);
}
The UpdatePanel still does a postback. The whole page life-cycle is repeated when the button is clicked, and therefore the Page_Init and Page_Load for example will be executed again. AJAX does not remove the postbox, just hides it from the client.
I can't obviously see something wrong with the code you've posted however I would suggest you place a break point in the Page_Init as a start. This will be able to tell you if the postback is actually happening or not, since this will be fired if the button is indeed trying to fire the button click event. Keep in mind any click events is fired after the page life cycle completes (Theoretically).
On second look I would suggest that you change the Button event in the FirstView() method to a Click rather then a Command and see if this triggers the event.
it is better to add any event to the control before adding the control to another container.
secondly the button with the parameter name "btnCommentSave" will not work. You have to be careful on OnInit, OnLoad events. It is server-client side issue. The page pushed from server to client does not include the "btnCommentSave" button, so that this button stays at the clients page but it does not work.
btnComments works, because it is rendered by server before pushing to client at UpdatePanel's OnLoad function.
What rendered after OnLoad functions, does not work.

Resources