How to select the asp:dropdown list dynamically in asp.net using c#

In this tutorial you will learn how to select the asp:DropDownList dynamically. It is quite simple. Let's have a look over how to do so.
.aspx page

<asp:dropdownlist style="font-family: verdana;" id="ddl_Status" runat="server"></asp:dropdownlist>
In our .aspx page we have a DropDownList, now I am going to populate this and select it's value dynamically according to my requirement.

How to select the asp:dropdown list dynamically in asp.net using c#

.aspx.cs


myBusinessLayer _objLayer = new myBusinessLayer();
_objLayer.GetStatus();
ddl_Status.DataSource = _objLayer.LayDS.Tables["SomeDataset_Table"];
ddl_Status.DataTextField = "description";
ddl_Status.DataValueField = "id";
ddl_Status.DataBind();
ddl_Status.SelectedIndex = ddl_Status.Items.IndexOf(ddl_Status.Items.FindByValue("1"));

I have written a function GetStatus() in Business Logic Layer, that is getting records from database. After that i give call to that function, give values returned by the function to the DataTextField and DataValueField of asp:DropDownList and then I write one line of code to select the asp:DropDownList.


In this example I am selecting the asp:DropDownList By Value using this FindByValue() built-in function but you can select the asp:DropDownList by Text as well using this FindByText() built-in function. In this example I am selecting the asp:dropdown list if the DataValueField contains the value 1.


So this is the way to select the asp:DropDownList dynamically in asp.net using C#.

0 comments: