I have a bit of trouble with getting dropdownlist selected value we have in aspx a Gridview and in it dropdownlist:
<asp:GridView ID="grid1" runat="server" autogeneratecolumns="true" >
<Columns>
<asp:BoundField HeaderText="something" />
<asp:TemplateField HeaderText="filtras">
<HeaderTemplate>
<asp:DropDownList ID="dropdown1" runat="server"
OnLoad="dropdownLoad"
OnSelectedIndexChanged="updatetable" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
We fill the DropDownList with values using OnLoad event, and then when we select something from the DropDownList, the event OnSelectedIndexChange should allow us to take the selected value and to do what we want with it (filter the grid in this case), but OnSelectedIndexChange never gets executed.
protected void Page_Load(object sender, EventArgs e)
{
//Create Gridview + fill with values
if (IsPostBack)
{
return;
}
ArrayList mycountries = new ArrayList();
mycountries.Add("Norway");
mycountries.Add("Sweden");
mycountries.Add("France");
mycountries.Add("Italy");
mycountries.TrimToSize();
mycountries.Sort();
rb.DataSource = mycountries;
rb.DataBind();
grid1.DataSource = mycountries;
grid1.DataBind();
}
protected void dropdownLoad(object sender, EventArgs e)
{ // fill dropDownList in GridView with data
DropDownList dropdown = sender as DropDownList;
if (dropdown != null)
{
ArrayList mycountries = new ArrayList();
mycountries.Add("Norway");
mycountries.Add("Sweden");
mycountries.Add("France");
mycountries.Add("Italy");
mycountries.TrimToSize();
mycountries.Sort();
dropdown.DataSource = mycountries;
dropdown.DataBind();
TextBox1.Text = dropdown.SelectedIndex.ToString();
}
}
protected void updatetable(object sender, EventArgs e)
{// after dropDownList element was selected change dropdownlist values/or filter the table...
//this part is never executed ! Why?
DropDownList dropdown = sender as DropDownList;
if (dropdown != null)
{
ArrayList mycountries = new ArrayList();
mycountries.Add("UK");
mycountries.Add("USA");
mycountries.Add("Sweden");
mycountries.Add("Hungary");
mycountries.TrimToSize();
mycountries.Sort();
dropdown.DataSource = mycountries;
dropdown.DataBind();
}
}
How can I get the DropDownList‘s selected value? My debugger shows that OnSelectedIndexChange is never executed.
I tried following the suggestions in this question Setting selectedvalue for a dropdownlist in GridView, but that didn’t work.
Have you tried setting AutoPostBack to true for your dropdown control so that it causes a postback?