Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to populate dropdownlist in asp.net (code behind)?

What is the simplest way to populate a dropdownlist in asp.net (code behind)? I have just learned howto fill a grid using datatable and data adapter. Can datatable and data adapter be used to populate a dropdonlist? Here is my attempt..

public partial class page3 : System.Web.UI.Page
{
  public DataTable fillmydropdownlist()
  {
     DataTable drpdt = new DataTable();
     string q = "select flightdate from flightdetails";
     SqlCommand cmd = new SqlCommand(q,con);
     try
     {
         SqlDataAdapter da2 = new SqlDataAdapter(cmd);
     }
     catch { }
     return drpdt;
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    dbOperation dbo = new dbOperation();
    DataTable dt = new DataTable();
    dt = dbo.fillmydropdownlist();
    DataTable drpdt= new DataTable();

    if (dt.Rows.Count > 0)
    {
        DropDownList1.DataSource = drpdt;
        DropDownList1.DataBind();
    }
    else
    {
        Response.Write("No Data");
    }
  }
}
like image 828
Arbaaz Avatar asked Oct 19 '12 17:10

Arbaaz


Video Answer


1 Answers

You can use DataTextField and DataValueField properties.

ListControl.DataTextField Property

DropDownList1.DataSource = drpdt; 
DropDownList1.DataTextField="StringValue";
DropDownList1.DataValueField="CurrencyValue";
DropDownList1.DataBind(); 

Or add ListItem one at a time.

ASP.Net DropDownList DataTextField Multiple Columns

like image 107
Win Avatar answered Oct 27 '22 22:10

Win