Dropdownlist selected value at Selectedindexchanged event
Asked Answered
N

3

9

I'm working on asp.net website with Vb.net and I have a dropdownlist with autopostback = true and I need to get the selected value when I change the item or I want to get the item which fires the selectedindexchanged event ..

any help please..

Nozzle answered 21/2, 2012 at 2:9 Comment(0)
D
9

In ie. your Page_Load set

this.ComboBox1.SelectedIndexChanged += new System.EventHandler(ComboBox1_SelectedIndexChanged);

Then write the event handler like this:

private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
  ComboBox comboBox = (ComboBox) sender;
  string selected = (string) comboBox.SelectedItem;
}

Make sure that in your Page_Load you write this before setting the combobox default value or you will end up with this always being the selected item:

if (Page.IsPostBack)
  return;
Doghouse answered 21/2, 2012 at 2:16 Comment(3)
I edited my answer, you need to be aware that the Page_Load is executed before the SelectedIndexChanged, so anything you do with the combobox here will affect your result. Use the if statement in the top section of Page_Load.Doghouse
shouldn't this: ComboBox1.SelectedItem; be this: comboBox.SelectedItem; ?Salita
It's amazing how the OP specified in the question that he's working on a asp.net website with Vb.net but all the answers on here are C#?? lolDeadlight
C
9

try this:

    protected void list_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList list = (DropDownList)sender;
        string value = (string)list.SelectedValue;
    }
Chenopod answered 7/8, 2014 at 3:44 Comment(1)
This gives me a SelectedValue of whatever the Initial setting is rather than the newly selected setting.Flavine
R
0

If item is a Dictionary:

string value = ((KeyValuePair<string, string>)combobox.SelectedItem).Key;
Reface answered 25/4, 2016 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.