Arbaaz
Arbaaz

Reputation: 321

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

Upvotes: 6

Views: 39705

Answers (6)

Win
Win

Reputation: 62300

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

Upvotes: 12

Ed Sansbury
Ed Sansbury

Reputation: 96

This is simple for the code behind.

private void Page_Init(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlProductID.DataSource = ProductsDB.GetProductsForDDL;
        ddlProductID.DataBind();
    }
}

Your DropDownList may look something like this on the page.

<asp:DropDownList ID="ddlProductID" runat="server" AppendDataBoundItems="True" CssClass="DropDown" DataValueField="ProductID" DataTextField="Product" ViewStateMode="Enabled">
                                                                <asp:ListItem Value="">Select</asp:ListItem>
                                                            </asp:DropDownList>

Maybe create some business objects in a class something like this

public class ProductInfo()
{
    public ProductInfo() : base()
    {
    }

    public Int32 ProductID { get; set; } = 0;
    public string Product { get; set; } = string.Empty;
}

Write another class with a static method which returns a List something like the below, but using ADO.NET (DataReader and stored procedure) rather than Enterprise Library. I will improve my answer if interested.

public class ProductsDB()
{
    public static List<ProductInfo> GetProductsForDDL()
    {
        List<ProductInfo> objs = new List<ProductInfo>();
        Database db = new DatabaseProviderFactory().CreateDefault;
    
        using (DbCommand cmd = db.GetStoredProcCommand("SYSTEM_Products_DropDownList"))
        {
            using (IDataReader dr = db.ExecuteReader(cmd))
            {
                while (dr.Read())
                    objs.Add(new ProductInfo(Convert.ToInt32(dr("ProductID")), (string)IIf(IsDBNull(dr("Product")), "", dr("Product"))));
            }
        }
    
        return objs;
    }
}

This will enable you to list products on any page of the application without having to copy and paste lots of code.

Upvotes: 0

Moojjoo
Moojjoo

Reputation: 753

Moojjoo's Suggestion ---

  private string FillBizNameCountyDdl()
    {
        string returnText;
        string nameAndCounty;
        string id;


        try
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Select *  FROM [tbl_name_county_web_search] ORDER BY main", conn))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                nameAndCounty = reader["main"].ToString();
                                id = reader["id"].ToString();
                                ddlBizNameAndCounty.Items.Add(new ListItem(nameAndCounty, provId));                  
                            }
                        }                            
                    }
                }
            }
        }
        catch (Exception ex)
        {
            return ex.Message.Trim();
        }
        returnText = "Success";
        ddlBizNameAndCounty.Items.Insert(0, new ListItem("--Select Provider--"));
        ddlBizNameAndCounty.DataBind();
        return returnText;
  }

Upvotes: 2

ARUNRAJ
ARUNRAJ

Reputation: 489

<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="StringValue" 
            DataValueField="CurrencyValue">
        </asp:DropDownList>



//C#:

DropDownList1.DataSource = drpdt; 
DropDownList1.DataBind(); 

Upvotes: 0

danyim
danyim

Reputation: 1293

The solutions that Win and codingbiz suggested are the easiest, but only for the easiest scenarios. Not every DropDown is required to be bound like that. Sometimes I have instances where I will need to bind two (or more) values to a Listitem, leading me to do something like what your example did by iterating through the DataTable rows, but instead doing...

foreach (DataRow dr in dt.Rows) {
    DropDownList1.Items.Add(new ListItem(dr["flightdate"], dr["flightnum"] + ":" + dr["flightcarrier"]));
}

Later I can do a String.Split(":")(0) or String.Split(":")(1) to get the first and second ListItem values.

All in all, it really depends on what your needs are.

Upvotes: 3

codingbiz
codingbiz

Reputation: 26396

All databound controls can be bound to DataTable and any object that Implements IEnumerable (e.g. Array of String). DropdownList is a databound control, so the answer is Yes.

if (dt.Rows.Count > 0)
{
    DropDownList1.DataTextField = "FlightDescription";
    DropDownList1.DataValueField = "FlightID";
    DropDownList1.DataSource = drpdt;
    DropDownList1.DataBind();
}

You can also set the DataXXXField properties from the MarkUp

<asp:DropdownList ID="DropDownList1" runat="server" 
                  DataTextField="FlightDescription" DataValueField="FlightID">
</asp:DropdownList>

Upvotes: 2

Related Questions