Can we bind a DropDownList using List<> in Asp .Net
The Answer is :
Yes, we can bind a DropDown in Asp .Net using List<>. Please go through the following code for Example:-
Let's create a Class say DropdownClass, in the class we create following properties :-
public class DropdownClass
{
public int value { get; set; }
public string text { get; set; }
}
Now in the aspx page, take a DropDownList control, Example:-
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
Now in the code behind, write the following code inside Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<DropdownClass> lst = new List<DropdownClass>();
DropDownList1.DataSource = lst;
DropDownList1.DataValueField = "value";
DropDownList1.DataTextField = "text";
DropDownList1.DataBind();
}
}
Now your DropDown is ready for action, you can get the SelectedValue as well as the SelectedItem in the OnSelectedIndexChanged method.
Hope it helps... Happy Coding!
0 Comment(s)