DropDownList项和gridView

时间:2014-07-02 18:44:46

标签: c# asp.net gridview drop-down-menu

向所有好人致以问候。 我正在学习ASP并且有一个我无法解决的问题。这是困扰我的:

我有一个gridView,列出所有客户的所有信息(城市,地址,电话等)。我的想法是在其中添加一个包含所有城市的dropDownList,并且当您在gridView中选择某个城市时,将仅显示该城市的客户。我连接了一切但现在我只能看到与dropDownList中的第一项相同的城市客户(从[someTable]中选择*,其中City = @City)。最后,这里有一个问题:是否有任何方法可以插入第一个被选中的项目和该项目的值为"选择以下所有"。当选择第一个项目时,它应该允许我查看来自所有城市的客户。有没有简单的解决方案?

3 个答案:

答案 0 :(得分:1)

首次绑定DropDownList后,在索引0处插入一个新的ListItem:

ddl.Items.Insert(0, new ListItem("- Please Select -"));

然后每当你再次绑定GridView时,首先检查DropDownList的索引,确保他们选择的不是第一个。

if(ddl.SelectedIndex > 0)
{
    gridview.DataSource = filteredList;
    gridview.DataBind();
}
else
{
    gridview.DataSource = unfilteredList;
    gridview.DataBind();
}

答案 1 :(得分:0)

我建议将City DropDownList作为表单过滤器并在gridview之外,并填充所有城市名称。

ddlCity.Items.Insert(0, new ListItem("select anything below", "0", true)

然后,当您获得数据时,您可以编写类似下面的内容

if (ddlCity.SelectedIndex != 0){
   var list = select * from [someTable] // select all customers for all cities
}
else
{
 // TODO : the required concatenation to send the selected city to sql       
 var list = select * from [someTable] where City = ddlCity.SelectedText // select only customers for selected city 
}
gv.DataSource = list;
gv.DataBind();

答案 2 :(得分:0)

按照其他答案中的建议添加第一个列表项:或

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0">- Select -</asp:ListItem>
</asp:DropDownList>

绑定下拉列表,但如果DropDownList1.SelectedValue为0,则不要将@City参数发送到SQL,代码为:

If DropDownList1.SelectedIndex > 0 Then
    'Send your parameter
End If

按如下方式更改SQL:

SELECT * FROM [SomeTable] WHERE @City IS NULL OR City=@City

如果要检索所有行,只需确保发送到SQL查询的变量为NULL。

相关问题