dropdown onselectedindexchanged event not firing and value kept on postback c# - c#

I can't get the dropdown onselectedindexchanged event to fire, and when I make a selection it resets the value of the dropdown onpostback, even though I have the if (!ispostback) in the page load event.
this is a content page in a master page in asp in case that matters.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server"
EnableViewState="true"
OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged"
AutoPostBack="true"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection constr = new SqlConnection(ConfigurationManager.ConnectionStrings["CBTestDBConnectionString"].ConnectionString);
SqlCommand eventsvcprogCMD = new SqlCommand("select*from SvcProg where eventatteligable=1", constr); // table name
SqlDataAdapter eventsvcadapt = new SqlDataAdapter(eventsvcprogCMD);
DataSet eventsvcset = new DataSet();
constr.Open();
eventsvcadapt.Fill(eventsvcset); // fill dataset
EventSVCProgList.DataTextField = eventsvcset.Tables[0].Columns["SvcProgID"].ToString(); // text field name of table dispalyed in dropdown
EventSVCProgList.DataValueField = eventsvcset.Tables[0].Columns["eventatteligable"].ToString();
EventSVCProgList.DataSource = eventsvcset.Tables[0]; //assigning datasource to the dropdownlist
EventSVCProgList.DataBind(); //binding dropdownlist
constr.Close();
}
}
protected void EventSVCProgList_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Eat Poop");
var somevalue = EventSVCProgList.SelectedValue;
}

There are couple of things.
1) You need to add a Script Manager to the page at the top if not added already(it will give you a runtime error if you have not added a script Manager to the page)
2) You need to change the Update Panel content as shown below
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="EventSVCProgList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>

There seems that any parent control or page leven ViewState is disabled. please check in debug mode that what value you getting for EventSVCProgList.EnableViewState and other parent controls' as well.

thanks for the help. its still not working so i'm just going to try to use javascript instead. its got to be some fundamental flaw with the way the master page or content page is setup.

Related

automatically update label when entering content in textbox asp.net

I have a textbox and a label in ASP.NET and i want to automatically update the label with a value from database that is fetched using the content entered in textbox. This should be done dynamically when the text is changed in textbox and if a match if found in database, the corresponding value should be displayed in the label field (without page refresh). In this case I will enter employee ID in textbox and employee name should be displayed in label. I am using the following code,
<asp:ScriptManager ID="script_manager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="update_name" runat="server">
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" AutoPostBack="true" OnTextChanged="text_empID_TextChanged" runat="server"></asp:TextBox>
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as follows,
protected void text_empID_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmployeeName from EmployeeTable where EmployeeID=#id", con);
cmd.Parameters.AddWithValue("#id", text_empID.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
label_empName.Text = dt.Rows[0]["EmployeeName"].ToString();
}
}
But this is not working. Also after entering a value in textbox and if i click outside the box, the text inside disappears. Is there any other way to do this? or am i doing something wrong here?
I would suggest that you should add a button because the text_changed event only fires when the text-box blurs (loses focus).
That's a very weird behaviour and most users are not used to it and will not expect it.
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" runat="server></asp:TextBox>
<asp:button id="btnSearch" runat="server" OnClick="text_empID_TextChanged" />
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
In any case, have you added a breakpoint? does the event fire? do you get any data back in the DataTable?
EDIT
After your last comment I am convinced that you are clearing the contents of the label on page load.
please, make sure that you only do that in the following context:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
label_empName.Text = "";
}
}

SelectedIndexChanged event of dropDownList not firing c#

I have checked every question in stackoverflow. :(
But anything seems not working..
i have placed a breakpoint in the event and not firing.
I hope you get the solution
Thanks
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:DropDownList AutoPostBack="true"
runat="server" ID="sel_area" class="select"
OnSelectedIndexChanged="sel_area_SelectedIndexChanged" EnableViewState="true">
</asp:DropDownList>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<Triggers>
<asp:AsyncPostbackTrigger ControlID="sel_area" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
here the c# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
destino = destinorfc();
tb_areas = mostrarAreas(destino);
for (int i = 0; i < tb_areas.Rows.Count; i++)
{
ListItem lst = new ListItem(Convert.ToString(tb_areas.Rows[i]["PEPCECO"]), Convert.ToString(tb_areas.Rows[i]["PEPCECO"]));
sel_area.Items.Insert(sel_area.Items.Count, lst);
}
}
}
public void sel_area_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("llegué");
string ArtistId = sel_area.SelectedValue;
Response.Write("<script language=javascript>alert('" + ArtistId +"');</script>");
Label1.Text = ArtistId;
Console.WriteLine("llegueee");
//LoadComboAlbum(ArtistId);
}
It Sound you are not registering event handler to you combobox
add below code into designer or Page_Load event
this.sel_area.SelectedIndexChanged +=
new System.EventHandler(sel_area_SelectedIndexChanged);
you can also do this by follow these steps
1: selecting your combobox/dropdown
2: go to properties
3: go to event tab
4: on Selectedindexchanged Event add you handler
Like others have already said, it sounds like your DropDownList SelectedIndexChanged event is not subscribed to your event handler. While I can see you've done it in your code, you may be losing the event subscription somewhere. To increase your understanding of the order of events the page fires, take a look at this other SO question and answer.
https://stackoverflow.com/a/11235074/2305468
Also note that if you ever take your "sel_area" object and replace it with a new DropDownList object in the C# code, you will lose all of your subscribed events from the previous DropDownList instance, so be sure that you do not completely replace it anywhere.

Ajax update panel causes blank space

I made an updatepanel to update a part of my code which uses a literal text to display html codes. I'm not sure why but when i use the same code on Page_Load, it came out funky.
protected void Page_Load(object sender, EventArgs e)
{
//Bind Staff Monitor Filter
filterLiteral.Text = PortalClass.getStaffFilter();
//Bind Staff Filter Data
loginPoolLiteral.Text = PortalClass.getLoginPoolData();
}
The original intent was for it to look like:
But the postback causes a blank space and my tags, (All, HTC Department etc) to instead of filtering the picture, brings me to the top of the page:
Here is my code for default.aspx:
<asp:UpdatePanel ID="UpdatePanelCrowdMonitor" runat="server"
RenderMode="Inline">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
//Some html codes
<asp:Literal ID="filterLiteral" runat="server"></asp:Literal>
<asp:Literal ID="loginPoolLiteral" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
And my Default.aspx.cs:
protected void Unnamed1_Tick(object sender, EventArgs e)
{
//Bind Staff Monitor Filter
filterLiteral.Text = PortalClass.getStaffFilter();
//Bind Staff Filter Data
loginPoolLiteral.Text = PortalClass.getLoginPoolData();
}

Avoid Refreshing on Databound Dropdownlist

I am working on a metrics screen that will display several charts based on different groups in a database. Part of it uses a function that hides selected charts until the user clicks to display them.
The problem is this: I'm using a Databind on the dropdownlist, so every time I select a new group, the page refreshes and everything returns to its default state.
My question is this: Is there a way that I can avoid refreshing the page every time I select a new option from the dropdown list? If so, how? If not, is there a better way to create the dropdownlist and attach values to it? If I set AppendDataBoundItems to false, then I always get the selected value as the first item in the list.
Here's my code for the dropdownlist:
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
Then C# code behind it is this:
public void Page_Load(object sender, EventArgs e){
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
ICollection CreateDataSource(){
DataTable Ministries = new DataTable();
Ministries = oDatabase.GetData(#"SELECT DISTINCT B.Description
FROM tblInvolvement AS A LEFT JOIN tblMinistries AS B
ON A.Activity = B.MinistryID");
DataView dv = new DataView(Ministries);
return dv;
}
Try to use the ASP.NET UpdatePanel. Just wrap your DropDownList in it, and it should works. Here is a quick example that I didn't test.
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
On a final note, you will soon find out the limits of this solution, and later you might prefer to use Javascript instead.
I think the issue is that you are rebinding the data on Page_Load but you are not checking if !IsPostBack in other words, your code should look like this:
public void Page_Load(object sender, EventArgs e){
if(!IsPostBack)
{
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
}

Unable to retrieve DDL SelectedValue bound in ASPX after Page Load

I have the following markup / code block in the ASPX file.
The binding of the ddl is triggered after Page_Load event which is in the code behind file.
This results me not able to get the selected value of the dropdownlist if I were to use such flow.
However for some purpose I require it to work this way.
Any idea how I could get the dropdownlist selected value when a post back is being triggered (click of the button)?
Page URL: page.aspx?para1=0&para2=value
ASPX PAGE
<%
if (Convert.ToInt32(Request.QueryString["para1"]) == 0)
{
ddl.DataValueField = "value";
ddl.DataTextField = "text";
ddl.DataSource = ds; //ds is valid, exact code not shown
ddl.DataBind();
} else {
//write in this area
Response.Write("Not 0");
}
%>
<form runat="server" id="user_form" class="form-horizontal">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="updPanel" runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
<%-- this button will call btnSave_Click to get the ddl's value--%>
<asp:Button runat="server" ID="btn" Text="Button" OnClick="btn_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do my stuff
}
}
protected void btn_Click(object sender, EventArgs e)
{
int intValue = Convert.ToInt32(ddl.SelectedValue);
//do my stuff
}
The ASPX Page code block will run after Page_Load / page's lifecycle, then will determine what to do base on the url parameters.
Thanks in advance!
You could always throw in a hidden object and use jquery to copy the value to the hidden value based on a certain action without a postback and would do it client side like it sounds like you want it to do

Categories