Why does the selectedindexchanged event not work when making controls visible - c#

Im trying to have my drop down list make four controls visible on the selectedindexchanged event for the control.
Basically when the user chooses "Server" from the drop down list the event should fire and the user should see two extra options.
Tried a tonne of approaches so far including text_changed event but nothing.
Here is what i got so far
//adds new fields to the form when the user selects server as the asset type
protected void AddNewFields(object sender, EventArgs e)
{
//If the asset is a server then make the extra controls available
if (TypeDDL.Text.Equals("Server"))
{
DNLabel.Visible.Equals(true);
//DNLabel.Visible = true;
DomainNameTB.Visible = true;
RoleLabel.Visible = true;
RoleDDL.Visible = true;
}
}
<asp:DropDownList ID="TypeDDL" runat="server" DataSourceID="AssetTypeDS"
DataTextField="AssetTypeDescription" DataValueField="AssetTypeID" OnTextChanged="AddNewFields">
</asp:DropDownList>

Add AutoPostback="True" to your DropDownList and the above code should trigger
As for an explanation: The drop down list doesn't automatically post back to the server. Changing a selection happens on the client side. Once you add the above, it'll repost the page. If you don't want the whole page to flicker each time someone changes a selection, you can either use some client side Javascript or Jquery, or use an asp:UpdatePanel

Please set AutoPostBack="True" property of a DropdownList...

add AutoPostBack="true" in dropdown
<asp:DropDownList ID="TypeDDL" runat="server" DataSourceID="AssetTypeDS" AutoPostBack="true"
DataTextField="AssetTypeDescription" DataValueField="AssetTypeID" OnTextChanged="AddNewFields">
</asp:DropDownList>

Related

ASP.NET populate lists referencing each other on selected index change

I have an ASP.NET control with three listboxes: LBParent, LBChild1 and LBChild2.
LBParent has to be filled programmatically. I do this in Page_Load.
When the user selects a value in LBParent, I want to fill both LBChild1 and LBChild2 with some data, programmatically. The children lists must also keep track of their selected value.
Basically, the parent list is a list of users, the first list is a list of permissions the user has, the second list is a list of permissions the user doesn't have.
My plan is to add two buttons to move permissions between the two lists.
Unfortunately, I cannot get this to work properly.
If I populate the parent list in Page_Load, the selected index seems to reset. I used ViewState to save the index... but this seems to require an additional refresh, because it doesn't update after the PostBack. This is not acceptable.
If I populate the children listboxes on the OnParentSIC event, there is no way I can keep track of their selected index. The OnChildXSIC events never fire, because the listboxes get repopulated "too soon". (?)
How can I get this to work as intended? Maybe there is a better solution but I'd really like to understand how to get this solution to work, as I can't see a possible solution at the moment.
Control.ascx
<%# Control Language="C#" AutoEventWireup="true" EnableViewState="True" CodeBehind="..." Inherits="..." %>
<form runat="server">
<asp:ListBox ID="LBParent" runat="server" CssClass="form-control"
AutoPostBack="true" OnSelectedIndexChanged="OnParentSIC" />
<asp:ListBox ID="LBChild1" runat="server" CssClass="form-control"
AutoPostBack="true" OnSelectedIndexChanged="OnChild1SIC" />
<asp:ListBox ID="LBChild2" runat="server" CssClass="form-control"
AutoPostBack="true" OnSelectedIndexChanged="OnChild2SIC" />
</form>
Control.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
// Populate parent
for(...) LBParent.Items.Add(...);
}
The Onchange-event fires, but before that the OnLoad fires.
So:
The user clicks on an selection
A postback is triggered
At the server the Onload fires (and rebuilds the list)
The OnSelectedIndexChanged fires (which lost the selection by now)
So I would try to save the current-selected-index before you rebuild the list (in the Onload).
If you restore it later on while you are in the same 'postback' you can save it in a simple variable. No need to store in a Viewstate or Session.
use Like this
If You are on the Same Page then You can Use ViewState/Hidden Fields
to Maintain States
First Time Adding ListItem on PageLoad Use Like this
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
AddListItems();
}
}
Protected Void AddListItems()
{
// Populate parent
for(...) LBParent.Items.Add(...);
for(...) SecondList.Items.Add(...);
for(...) ThirdList.Items.Add(...);
}

Given a DropDownList how to find associated "OnSelectedIndexedChanged" event Method Name

I have a dropdownlist in my page, as Shown below:
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
Code Behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Logic Goes Here
}
In Page Load, From Session Variable I will get DropDownList id as "DropDownList1". Based on this ID string I can get the Control, but not able to get the Event Name associated with it.
So How to find the Event Name of Control by knowing Control??
Thnaks in advance
You may need to get it by Attributes.
string selected = EventDropDownList1.Attributes["onselectedindexchanged"].ToString();
Not sure what your asking here but the event can be wired up in two ways,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)Handles DropDownList1.SelectedIndexChanged
Or in the page load part:
AddHandler DropdownList1.SelectedIndexChanged, AddressOf DropDownList1_SelectedIndexChanged
I know your question is asking to find the name of the event from the control name but you wire the event to the control. If you need to test which control fired the event i.e. you have the same code wired up to multiple drop down lists and you want to control the code flow based on the DDL ID then cast the sender to access it's values:
Dim id As String = CType(sender,DropDownList).ID
Hope that helps, if you can give more info I can perhaps give a more definitive answer.
Sorry answer in VB.Net.
You can use blow code:
Request.Form("__EVENTTARGET")
If you are using AutoPostBack = true you don't need to specify events. Auto postback will run the correct event based on what happened in the postback.
So you don't need to know the name of the event, just create the event in the back end and autpostback will fire the appropriate code.

dropdown event handler writing in asp.net and C#

What properties should I enabled in dropdown menu and how should I initiate the code in C#? I'm using Visual studio as my back end.
ASPX:
Set the auto postback and add an event handler:
<asp:DropDownList runat="server" id="foo" AutoPostback="true" OnSelectedIndexChanged="foo_SelectedIndexChanged>
</asp:DropDownList>
In the .CS
protected void foo_SelectedIndexChanged(Object sender, EventArgs e){
}
Hope this works for your requirements.
1. Getting dataset value from Database.
2. Biding for the required DropDownList
3. Selecting default value for the DropDownList.
Make Sure to check autopost back property to "True"
http://www.codeproject.com/Questions/400833/How-to-bind-or-populate-data-into-a-Dropdown-List

Nested ASP.NET DropDownList SelectedIndexChanged Not Firing

Have run this by my entire dev group to no avail. Seems simple enough, here's the question.
I have a UserControl with a single, non-databound dropdownlist. The UserControl is then dropped onto the masterpage and then also loaded into an inheriting webform that has the control manually loaded onto the page.
No AJAX, straight post-back.
The issue I am running into is that the SelectedIndexChanged event is not firing for the second instance of the DropDownList. The first one fires just fine.
TIA
Here is the code for the ascx:
<asp:dropdownlist id="SelectLanguage" autopostback="true" runat="server" enableviewstate="true">
<asp:listitem>- Select Language -</asp:listitem>
<asp:listitem value="xxx">Netherlands</asp:listitem>
<asp:listitem value="xxx">United Kingdom</asp:listitem>
<asp:listitem value="xxx">United States</asp:listitem>
</asp:dropdownlist>
Here is the CB for the user control:
protected override void OnInit(EventArgs e)
{
SelectLanguage.SelectedIndexChanged += new EventHandler(SelectLanguage_SelectedIndexChanged);
base.OnInit(e);
}
protected void SelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
// do something
}
Does the postback actually happen for the second dropdown, or does the page do nothing?
If the postback isn't happening, you have javascript errors on your page.
Not sure exactly how this is, but the FancyBox lightbox jQuery library we're using to do the lightbox effect around the 2nd drop down is somehow messing with the bindings on the back end. No real time to figure out why, just let it be known it does in case anyone else runs into this issue.

Dynamically adding a command button to a GridView

I'm having an issue with trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.
I'm then taking the data in the first cell of each row, and creating a button that will link to a URL. To get the URL, I have to run a query with the data in the first cell as a parameter. I was doing this in the RowDataBound event at first, but hitting that query for every row was making it really slow.
So I decided to add a button that would retrieve the URL only when you clicked the button.
Here's my GridView:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
And my code:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
The grid generates fine, the button gets added to the grid for each row. But when I click on it, the RowCommand event doesn't fire, and the page just refreshes.
Does anyone know what the issue is?
Why use a dynamic button at all? You can easily put the linkbutton directly into the markup of the gridview (as long as you don't mind using a template field) and there will be no need to mess around with the RowDataBound event.
Your markup would look something like the following:
<Columns>
<asp:TemplateField HeaderText="SomeHeaderText">
<ItemTemplate>
<asp:LinkButton ID="lnkBtn" runat="server" CommandName="NumClick" CommandArgument= '<%# (string)Eval("dbValue") %>' Text='<%# (string)Eval("dbValue") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
</Columns>
Add breakpoints to the RowCommand event and make sure that you can hit the breakpoints.
The problem may lie elsewhere.
Also, make sure that you're not databinding on postback.
You have a big trouble with your code. It's pretty hard for me to explain what's your big mistake, but I can easily tell you how to fix.
The problem is that you generate a new button inside the RowDataBound event, definitely the wrongest choice. The button gets rendered because it exists after that event when page renders, but doesn't exist before data binding. If you bind data everytime you load the page (even during postback) the button still gets rendered because you generate a new button.
But since the button doesn't exist before data binding, it cannot raise events. You must declare the button from markup into a template of GridView, then access it not by using new LinkButton() but by using e.Row.Cells[0].FindControl("buttonId") and set its text. Then, you have to set its markup in order to fire its own Command event (not RowCommand) and handle it as you used (don't forget to set CommandArgument during data binding)
[Edit] I also made a mistake: controls inside data bound controls also don't exist before data binding. But they are initialized not with new Control() (by the private methods of data bound control) but with Page.LoadControl(typeof(Control)). That's the first thing you must fix when you load controls dynamically!!
Because the control is added dynamically on databind and you have to databind the gridview for each postback, the control being "clicked" is different each time. The event doesn't fire because at the time it needs to fire it doesn't exist as it did in the last iteration of the page.
I notice you don't have any logic determine if the button should be there, and it always goes into cell[0].
You should place this button into a TemplateItem so that it exists properly. If you have a need to do it in code-behind, you are probably better served doing it in the RowCreated event.

Categories

Resources