POPULATING DROP DOWN LIST FROM THE DATABASE

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
 842  View(s)
Ratings:
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"]));

    }

}

  1. Sumit Kesarwani

    Post:378

    Points:2694
    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";

    ddlSub.DataBind();

Answer

NEWSLETTER

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