Populating drop down list from the database

Total Post:117

 1075  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++)

  1. Post:378

    Re: Populating drop down list from the database

    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";

      Modified On Apr-06-2018 06:43:31 AM



Enter your email address here always to be updated. We promise not to spam!