How to select all records in a DropDownList

2019-03-02 19:55发布

问题:

I have this DropDownList:

<asp:DropDownList ID="DropDownList1" 
    runat="server" 
    AutoPostBack="true" 
    DataSourceID="SqlDataSource1" 
    DataTextField="Categorie" 
    DataValueField="Cat_ID" 
>
</asp:DropDownList>

and the SqlDataSource select * all from [tbl_Cat]

It's used to filter the database via category. It works perfectly, but it only shows the three categories that are in the tbl_Cat. I also want a select all item in the DropDownList.

The DropDownList and the datagrid are not made with code-behind; is it possible to enter a "select all records" option through code-behind?

回答1:

You need to write the below code which help you to select all option for category.

 <asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server">
 </asp:DropDownList>

In Code behind file

SqlConnection con = new SqlConnection(str);
string com = "select * all from tbl_Cat";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);

DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "Categorie";
DropDownList1.DataValueField = "Cat_ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select ALL", "0"));

Now you can check if drop down selected value is 0, if it is 0 then you can load all the records in the grid.

Let me know if any thing i miss.



回答2:

following is the way to bind DropDownList from codebehind. visit this link for details

 <asp:DropDownList ID="DropDownList1" runat="server">
 </asp:DropDownList>

CODE BEHIND

SqlConnection con = new SqlConnection(str);
string com = "select * all from tbl_Cat";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);

DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "Categorie";
DropDownList1.DataValueField = "Cat_ID";
DropDownList1.DataBind();


回答3:

May be you have this query,

DropDownList1.Items.Add(new ListItem("Select All", "0"));