简体   繁体   中英

Bind default value to dropdown list from datatable c#

Code

protected void Page_Load(object sender, EventArgs e)
{        
    ddlYear.DataSource = GetYear();
    ddlYear.DataBind();
    ddlYear.Items.Insert(0, "--Select--");
    ddlYear.Items.Insert(1, "All");
}

public static DataTable GetYear()
    {
        DataTable dt = new DataTable();
        string strcon = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(strcon))
        {
            conn.Open();
            string strQuery = "SELECT Previous_Year AS Year FROM Year UNION ALL SELECT Current_Year FROM Year";
            SqlCommand cmd = new SqlCommand(strQuery, conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
        }
        return dt;
    }

My datatable returns the below value

2014
2015

Now on page load my dropdown values should be like the below and by default I need to show 2014 value in the dropdown list.

--Select--
   All
  2014
  2015 

Try this,

ddlYear.DataSource = GetYear();
ddlYear.DataBind();
ddlYear.Items.Insert(0, "--Select--");
ddlYear.Items.Insert(1, "All");
ddlYear.Items.FindByValue("2014").Selected = true;

First add your data from your database by using the DataSource and DataBind() function.

You can add a default option to your select by creating a new ListItem and insert it at the beginning of your items.

ListItem item = new ListItem();
item.Text = "All";
item.Value = "-1";

this.ddlSelectBoxId.Items.Insert(0, item);

To select 2014:

this.ddlSelectBoxId.SelectedValue = "2014";

Here ddlSelectBoxId is the Id of your ASP Dropdownlist control.

To display the current year, you can use the following:

this.ddlSelectBoxId.SelectedValue = DateTime.Now.Year.ToString();

To display the first item from your DataTable :

Make sure you have sorted using the SQL command to your needs, after that use:

this.ddlSelectBoxId.SelectedValue = DataTable.Rows[0][0];

This takes the first row and the first column of your first row. DataTable is your variable returned by your function.

If the sequence is directly 2014,2015..... then you can set the appenddatabounditems property of drop down list to true.

Also, On page load

ddlYear.DataSource = GetYear();
Dim L As New List(Of string)
For Each item As ListItem In ddlYear
L.Add((item.Value).ToString());
Next
ddlYear.selectedvalue = L.Min();
ddlYear.DataBind();

I Hope you want to select the current year as selected by default. You can do that by

ddlYear.SelectedValue=DateTime.Today.Year.ToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM