VB.NET - getting the selected item of dynamically created dropdown

Asked By rama chandran on 29-Aug-11 04:05 AM
in vb.net i want the create dropdown dynamically and add some static items in code behind. then i want to get the selected item of that dropdown and display in some controls. pls give the exact code.
Jitendra Faye replied to rama chandran on 29-Aug-11 04:29 AM
Suppose you have addedd created DropDownList in panel .

For that use this code-

protected void btnGetValue_Click(object sender, EventArgs e)
      DropDownList drp= (DropDownList)Panel1.FindControl("DropDownList1");
          string str= drp.SelectedItem.ToString();

Try this code and let me know.

Sreekumar P replied to rama chandran on 29-Aug-11 04:34 AM
Anoop S replied to rama chandran on 29-Aug-11 05:58 AM
You can get the value like this way

protected void Button1_Click(object sender, EventArgs e)
      foreach (GridViewRow row in GridView1.Rows)
        DropDownList d1 = new DropDownList();
        DropDownList d2 = new DropDownList();
        DropDownList d3 = new DropDownList();

        d1 = (DropDownList)row.FindControl("d1");
        d2 = (DropDownList)row.FindControl("d2");
        d3 = (DropDownList)row.FindControl("d3");
        Response.Write(d1.SelectedValue.ToString() + "-" + d2.SelectedValue.ToString() + "-" + d3.SelectedValue.ToString());

refer this for more details
rama chandran replied to Jitendra Faye on 29-Aug-11 06:20 AM
actually i given like this, but for 1 dropdown it is ok, the selected item id displaying. but i want to display 5 dropdown and for the 5 dropdown the selecteditem should display in label in next next line. that is i want to loop through. how to do that.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim ComboBox As DropDownList = New DropDownList()

ComboBox.ID = "ComboBox"

ComboBox.AutoPostBack = True

ComboBox.Items.Add(New ListItem("Year: 2010", "2010"))

ComboBox.Items.Add(New ListItem("Year: 2011", "2011"))

ComboBox.Items.Add(New ListItem("Year: 2012", "2012"))

ComboBox.Items.Add(New ListItem("Year: 2013", "2013"))

ComboBox.Items.Add(New ListItem("Year: 2014", "2014"))

AddHandler ComboBox.SelectedIndexChanged, AddressOf Dynamic_Method


End Sub

Private Sub Dynamic_Method(ByVal sender As System.Object, ByVal e As System.EventArgs)

Dim ComboBox As DropDownList = CType(sender, DropDownList)

Dim sSTR As String = ""

sSTR = "</br>Selected Index: " + ComboBox.SelectedIndex.ToString()

sSTR += "</br>Selected Item: " + ComboBox.SelectedItem.Text.ToString()
sSTR += "</br>Selected Value: " + ComboBox.SelectedItem.Value.ToString()

Dim lbl As Label = New Label()

lbl.Text = sSTR

End Sub