Dropdown Selected IndexChanged is not firing - asp.net

I have one dropdownlist and its autopostback property is set to true.But when value is changed the selectedindexchanged property is not fired instead it is always going to pageload.Please tell what is the issue.
<asp:DropDownList ID="ddlVendor" CssClass="ddl" runat="server"
OnSelectedIndexChanged="ddlVendor_SelectedIndexChanged" AutoPostBack="true">
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
List<ProcurementItem> vendorsList = new List<ProcurementItem>();
vendorsList = (List<ProcurementItem>)ViewState["VendorList"];
string ID = string.Empty;
string accountID = string.Empty;
int? accountType = null;
if (ddlVendor.SelectedIndex > 0)
{
ID = ddlVendor.SelectedValue;
ProcurementClient procurementClient = new ProcurementClient();
List<ProcurementContract> contractList =
procurementClient.GetContractList(Convert.ToInt32(ID), null);
contractList = contractList.Where(i => i.Status == 4).ToList();
ddlContracts.DataSource = contractList;
ddlContracts.DataTextField = "ContractIDName";
ddlContracts.DataValueField = "ContractID";
ddlContracts.DataBind();
ddlContracts.Items.Insert(0, "");
}
}

Add following property in DropDownList
1.ViewStateMode="Enabled"
2.EnableViewState="true"
3.AutoPostBack="true"

try this
<asp:dropdownlist id=ddltrim width="100%" Runat="server" AutoPostBack="True" EnableViewState="True" onselectedindexchanged="ddltrim_SelectedIndexChanged">
Make Sure That your DropDownList within the Fom tag
<form>
//
</form>

dear check the causesvalidation= false
may be this is the problem
if you have any validations in your page dear
Thanks
:D

If you are filling the dropdown list from database then, make sure that the DataBind() method of dropdown list is called only when its not a post back as...
protected void Page_Load(object sender, EventArgs e)
{
...
If(!Page.IsPostBack)
{
......
dropdownlist.DataBind();
.....
}
...
}
Hope this helps :)

Related

dropdownchanged event not firing in usercontrol in asp.net

I have a dropdownlist in a usercontrol as shown below
<asp:dropdownlist id="ddlLanguage" runat="server" AutoPostBack="true" EnableViewState="true" onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
</asp:dropdownlist>
my selectedchanged event is not getting fired even once
in code behind
if (!IsPostBack)
{
//dt - is list of languages availbale in DB
//value[0]-contains lang currently to be binded to dropdownlist based
//remaining values (values [1]) to are to be populated to textbox
LoadModuleInfo(dt,values)
}
private void LoadModuleInfo(System.Data.DataTable dtLanguages, string[] values)
{
this.txbxModuleName.Text = values[1];
this.ddlLanguage.DataSource = dtLanguages;
this.ddlLanguage.DataTextField = "language_description";
this.ddlLanguage.DataValueField = "language";
this.ddlLanguage.DataBind();
// set up selections on the screen
this.ddlLanguage.SelectedIndex = this.getIndex(dtLanguages, values[0]);
}
protected void ddlLanguage_SelectedIndexChanged(object sender, System.EventArgs e)
{
//get new values ( values[0] and values[1])
LoadModuleInfo(dtLanguages, values);
}
protected int getIndex(DataTable dt, string recordId)
{
int intCt = 0;
foreach (System.Data.DataRow dr in dt.Rows)
{
if (dr[0].ToString() == recordId)
{
break;
}
else
{
intCt++;
}
}
return intCt;
}
i have wriiten the above code, but selectedchanged event is not fired for dropdownlist control available in USERCONTROL.
Please help.
If you page not refreshed at all .. most probably you have a javascript error in the page
Kindly remove below line from your code and try
this.ddlLanguage.DataValueField = "language";
or
change this too language to language_description

Radio button doesn't get selected after a post back

I have an item template within repeater:
<ItemTemplate>
<li>
<input type="radio"
value="<%# GetAssetId((Guid) (Container.DataItem)) %>"
name="AssetId"
<%# SelectAsset((Guid) Container.DataItem) %> />
</li>
</ItemTemplate>
I have a method that compares ids and decides whether to check the radio button.
protected string SelectAsset(Guid uniqueId)
{
if (uniqueId == GetSomeId())
return "checked=\"checked\"";
return string.Empty;
}
SelectAsset gets hit, but it doesn't select a radio button on a post back, but it does work if I just refresh the page. What am I doing wrong here?
Answer here: How to display "selected radio button" after refresh? says that it's not possible to achieve, is this really the case?
Thank you
Update
It appears that view state isn't available for simple controls if they don't have a runat attribute. I have solved this by using a custom GroupRadioButton control. Thank you for your help.
I'd suggest using a RadioButtonList:
Page Code
<asp:RadioButtonList RepeatLayout="UnorderedList" OnSelectedIndexChanged="IndexChanged" AutoPostBack="true" ID="RadioRepeater" runat="server" />
<asp:Label ID="SelectedRadioLabel" runat="server" />
Code Behind
if (!Page.IsPostBack)
{
/* example adds items manually
- you could iterate your datasource here as well */
this.RadioRepeater.Items.Add(new ListItem("Foo"));
this.RadioRepeater.Items.Add(new ListItem("Bar"));
this.RadioRepeater.Items.Add(new ListItem("Baz"));
this.RadioRepeater.SelectedIndex = this.RadioRepeater.Items.IndexOf(new ListItem("Bar"));
this.RadioRepeater.DataBind();
}
protected void IndexChanged(object sender, EventArgs e)
{
this.SelectedRadioLabel.Text = string.Format("Selected Item Text: {0}", this.RadioRepeater.SelectedItem.Text);
}
I assume you only need to select one item.
As described in the comments, it even works to access the SelectedItem in the Page_Loadevent handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// previous code omitted
}
else
{
string foo = this.RadioRepeater.SelectedItem.Text;
}
}
If you are creating all your controls dynamically at run-time (directly from code), then things are a little different. Here is the code that I used:
Page Code
<form id="form1" runat="server">
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList rbl = new RadioButtonList();
rbl.AutoPostBack = true;
rbl.SelectedIndexChanged += rbl_SelectedIndexChanged;
rbl.Items.Add("All");
// generate your dynamic radio buttons here
for (int i = 0; i<5; i++)
{
rbl.Items.Add(string.Format("Dynamic{0}", i));
}
form1.Controls.Add(rbl);
if (!Page.IsPostBack)
{
rbl.SelectedValue = "All";
PopulateTextBox(rbl.SelectedValue);
}
}
void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList foo = (RadioButtonList)sender;
PopulateTextBox(foo.SelectedValue);
}
void PopulateTextBox(string selection)
{
TextBox box = new TextBox();
box.Text = selection;
form1.Controls.Add(box);
}

link in gridview to details page

What I'm trying to do is create a Gridview and in the grid have a HyperLinkField it send me to a detail page for that item, I have the part that filled the grid and the link and how to pass the id of the element to another page
The problem I have is that when I run and click on the link shows me the details page that I want but is blank. when I debugged, I don't reach the details page
here is my code
fill the grid
var datos = db.Ticket
GridView1.DataSource = datos;
GridView1.DataBind();
show the GridView
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperLinkField HeaderText="Ver Ticket" Text="Ir Historial Ticket" DataNavigateUrlFormatString="~/DetailTicket.aspx?id={0}" DataNavigateUrlFields="IdTicket" />
</Columns>
</asp:GridView>
the detail page
public partial class DetailTicket: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
var id= Request.QueryString["id"];
var datos = db.detailTicket.Where(e=>e.IdTicket==id)
GridView1.DataSource = datos;
GridView1.DataBind();
}
}
Hey it might be issue with your path...
I have test your code and its working fine with me....
You are missing brackets on the if statement in the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
var id= Request.QueryString["id"];
var datos = db.detailTicket.Where(e=>e.IdTicket==id)
GridView1.DataSource = datos;
GridView1.DataBind();
}
}
Without the brackets, your id variable will not be known on the next line. I'd be surprised if it even compiles.

Dropdownlist Selected value is not working

I have 2 dropdowns ddl1 and ddl2. When im setting selected value for ddl1 it works,but after setting selected value for ddl2 also changes the value of ddl1.I dont know how but its doing so.
aspx
<asp:DropDownList ID="ddlPickup" runat="server" CssClass="tb_date"
>
</asp:DropDownList>
Dropoff:
<asp:DropDownList ID="ddlDropoff" runat="server" CssClass="tb_date" >
</asp:DropDownList>
<asp:RadioButtonList ID="radiobuttonlist1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="radiobuttonlist1_SelectedIndexChanged"
RepeatDirection="Horizontal">
<asp:ListItem Value="1">Day or Longer</asp:ListItem>
<asp:ListItem Value="2">1/2 Day</asp:ListItem>
<asp:ListItem Value="3">Hourly</asp:ListItem>
</asp:RadioButtonList>
code behind
protected void radiobuttonlist1_selectedindexchange(object sender, EventArgs e)
{
if(radiobuttonlist1.SelectedValue=="1")
{
Setddl();
}
}
public void Setddl()
{
if (ddlPickup.Items.Count > 0)
{
ddlPickup.Items.Clear();
}
if (ddlDropoff.Items.Count > 0)
{
ddlDropoff.Items.Clear();
}
ListItem li = new ListItem();
DateTime date = Convert.ToDateTime(StartDate.Text);
int day = Convert.ToInt32(date.DayOfWeek);
long itemid = Convert.ToInt64(ddlRentalItem.SelectedValue);
if (itemid != 0)
{
var dropoff = _objRitems.GetHourlyHourByDay(itemid, day);
if (dropoff.Count > 0)
{
int stimeh = Convert.ToDateTime(dropoff[0].OpenTime).Hour;
int etimeh = Convert.ToDateTime(dropoff[0].CloseTime).Hour;
DateTime dt = Convert.ToDateTime(dropoff[0].OpenTime);
for (int i = 0; i <= (etimeh - stimeh) * 2; i++)
{
string time = string.Format("{0:t}", dt);
li = new ListItem(time, time);
ddlPickup.Items.Add(li);
ddlDropoff.Items.Add(li);
dt = dt.AddMinutes(30);
}
ddlPickup.DataBind();
ddlDropoff.DataBind();
ddlPickup.SelectedValue=Request.QueryString["droptime"].ToString();
ddlDropoff.SelectedValue=Request.QueryString["droptime"].ToString();
//as soon as ddlDropoff SelectedValue assigns ddlPickup.SelectedValue changes to ddlDropoff.SelectedValue..Very Weird!!!
}
else
{
}
}
else
{
}
}
you need to write your dropdown code in below if condition.
if(!isPostBack)
{
}
Forget about ddlPickup_DataBound. Rely on the ViewState implicit in dropdown lists to repopulate the selected value. The ondatabound methods are unnecessary in this case.
Also you only need to bind the dropdowns once so on Page.IsPostBack - like the other poster has said
This would be the more standard way to deal with drop downs i.e.
Bind once
SelectedValue persists in after postbacks. No need for special work here
The way you are doing it - the databound will fire on each page load (after each dropdown if autopostback is true). The both dropdowns will repopulate every time - depending what yor have got in your Request collection. This isn't what you intend i assume and would account for the strange behaviour.
EDIT:
Just to be really clear this is the pattern that should be followed
Markup
<asp:DropDownList ID="ddlPickup" runat="server" ></asp:DropDownList>
<asp:DropDownList ID="ddlDropoff" runat="server" OnSelectedIndexChanged="selectedIndexEvent"></asp:DropDownList>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
BindDropDownLists();
}
}
protected void ddl2_selectedindexchange(object sender, EventArgs e)
{
//.. legit - do whatever is needed but don't reset selected value
}
protected void radiobuttonlist1_selectedindexchange(object sender, EventArgs e) {
{
BindDropDownLists();
SetInitialDropDownValues();
}
No ondatanound is needed

Maintain selected item in DropDownList inside GridView after removing some ListItems

I have a GridView with a DropDownList in each row. (The items in the DropDownList are the same for each.) I have a DropDownList "ddlView" outside of the GridView that is used for filtering the available options in the other DropDownLists. The default selection for ddlView is no filter.
When a user selects a new value for ddlView any selected values in the other DropDownLists disappear if they are not one of the values present after the filter is applied. What I would like to happen in that case is the previously selected value still be present and selected.
What is the best way to accomplish this?
The previously selected values are available during postback but appear to be cleared once DataBind() is called on the GridView, so I am unable to determine their previous value in the method where they are populated (the RowDataBound event).
My best idea so far is to manually store that information into an object or collection during postback and reference it later during the databinding events.
Is there a better way?
I don't think there is a better way to accomplish this as when the GridView is bound all of the controls are recreated thus removing the selections.
The following works: (I store the selections on postback to retrieve again in the RowDataBound event)
Markup
<asp:Button ID="button1" runat="server" Text="Post Back" OnClick="button1_Click" />
<br />
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="gridViewDropDownList" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
<asp:ListItem Value="3">Item 3</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code
public class GridViewDropDownSelections
{
public int RowIndex { get; set; }
public int SelectedIndex { get; set; }
}
...
private List<GridViewDropDownSelections> selectedDropDownListItems = new List<GridViewDropDownSelections>();
protected override void OnLoad(EventArgs e)
{
var selections = gridView1.Rows.Cast<GridViewRow>().Where(r => r.RowType == DataControlRowType.DataRow)
.Select(r => new GridViewDropDownSelections() { RowIndex = r.RowIndex, SelectedIndex = ((DropDownList)r.FindControl("gridViewDropDownList")).SelectedIndex }).ToList();
selectedDropDownListItems.AddRange(selections);
gridView1.RowDataBound += new GridViewRowEventHandler(gridView1_RowDataBound);
if (!IsPostBack)
{
BindDataGrid();
}
base.OnLoad(e);
}
protected void button1_Click(object sender, EventArgs e)
{
BindDataGrid();
}
private void BindDataGrid()
{
//Dummy data
string[] data = new string[] { "Item 1", "Item 2", "Item 3" };
gridView1.DataSource = data;
gridView1.DataBind();
}
void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var selection = selectedDropDownListItems.FirstOrDefault(i => i.RowIndex == e.Row.RowIndex);
if (selection != null)
{
try
{
DropDownList gridViewDropDownList = (DropDownList)e.Row.FindControl("gridViewDropDownList");
gridViewDropDownList.SelectedIndex = selection.SelectedIndex;
}
catch (Exception)
{
}
}
}
}
Hope it helps.
Instead of using DataBinding to apply the filter, you could add/remove the DropdownList items through the Items property, when another filter is selected. This way the selected value in the dropdowns should not be resetted.
You might be able to accomplish this with a simple condition. I don't know how you're filtering the items, but it would go something like this:
for (int itemIndex = 0; itemIndex < DropDownList1.Items.Count; itemIndex++)
{
ListItem item = DropDownList1.Items[itemIndex];
if (DropDownList1.Items.IndexOf(item) > ddlView.SelectedIndex)
{
if (!item.Selected)
{
DropDownList1.Items.Remove(item);
}
}
}
Not sure if this is what you're looking for, but hope it helps.
Use client side javascript
Search for all the appropriate select inputs and for each one found, go through the options and remove the one selected in the master ddl
function UpdateDropDowns (tbl) {
var controls = tbl.getElementsByTagName('select');
for (var i = 0; i < controls.length; i++) {
RemoveOption(controls[i], 'the value to remove');
}
}
function RemoveOption(ddl, val)
{
for (var i = ddl.options.length; i>=0; i--) {
if (ddl.options[i].value == val) {
ddl.remove(i);
}
}
}

Resources