How to bind a DropDownList to a DataSet C#

This example is for ASP but works in the same way for C#, the first thing you need is your DropDownList - obviously :P -

<asp:DropDownList ID="ddlTaskType" runat="server"></asp:DropDownList>


My DropDownList is ddlTaskType, now we have to add the list of items, using a DataSet "ds":



ddlTaskType.DataSource = ds;
ddlTaskType.DataBind();


Something really important is to define what column is the Value and what's the Text for each item of the drop down list,


ddlTaskType.DataValueField = "TypeID";
ddlTaskType.DataTextField = "TypeName";

So, bottom line, in order to fill a DropDownList with a DataSet you need first to select the data source, then define the Value/Text colmns and at last Bind...


ddlTaskType.DataSource = ds;  /* where ds is my data set */
ddlTaskType.DataValueField = "TypeID";
ddlTaskType.DataTextField = "TypeName";
ddlTaskType.DataBind();

And the result should be:



0 comentarios: