Home > DeveloperSection > Forums > Populating drop down list from the database
jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    November-17-2014 11:30 PM

 ASP.Net ASP.Net 
Ratings:


 1 Reply(s)
 530  View(s)
Rate this:

I used this c# code to add items in dropdownlist(ddlSub) from the table sub_info. But what I want is to add the value of the items in dropdownlist(ddlSub) from the same table which also has a column named sub_id of datatype varchar(50).

 

private void bind_ddlSub()

{

 

    ddlSub.Items.Insert(0, "-Choose-");

    datatable_object = methodClassFunc.getData("select sub_name from sub_info");

    for (int i = 0; i <= datatable_object.Rows.Count - 1; i++)

    {

        ddlSub.Items.Add(Convert.ToString(datatable_object.Rows[i]["sub_name"]));

    }

}



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    November-17-2014 11:44 PM

Hi Jay, 

You can use the ListItem object to add text and value for a dropdownlist item.

string subname = datatable_object.Rows[i]["sub_name"];

string subid = datatable_object.Rows[i]["sub_id"];

ddlSub.Items.Add(new ListItem(subname,subid));

Or you can bind your datasource like this:

ddlSub.DataSource = datatable_object;

ddlSub.DataTextField = "sub_name";

ddlSub.DataValueField = "sub_id";

ddlSub.DataBind();


Don't want to miss updates? Please click the below button!

Follow MindStick