user2710931
user2710931

Reputation: 7

DropDownList items and gridView

Big hello to all good people. I am learning ASP and have one problem that I cannot solve. Here is what bother me:

I have one gridView that list all customers with all their info (city, address, phone etc). My idea was to add one dropDownList with all city's in it and than when you chose some city in gridView would be displayed only customers from that city. I connected everything but now I can see only customers that have city same as first item in dropDownList (select * from [someTable] where City=@City). And finally, here is question: Is there any way that I can insert first item that would be selected and value of that item to be something like "select all below". When that first item is selected, it should allow me to see customers from all city's. Is there any simple solution?

Upvotes: 0

Views: 470

Answers (3)

user2233219
user2233219

Reputation:

Add the first list item as suggested in the other answers or:

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

Bind your Drop Down List but don't send your @City parameter to your SQL if DropDownList1.SelectedValue is 0, in code:

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

Change you SQL as follows:

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

Just make sure the variable sent to the SQL query is NULL if you want to retrieve all rows.

Upvotes: 0

Dennis R
Dennis R

Reputation: 3237

I would suggest to have the City DropDownList as a form filter and outside of the gridview and populate it will all city names.

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

Then when you get the data you can write something like the below

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();

Upvotes: 0

j.f.
j.f.

Reputation: 3949

After you bind your DropDownList for the first time, insert a new ListItem at index 0:

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

Then whenever you bind your GridView again, first check the index of the DropDownList, making sure they selected something other than the first one.

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

Upvotes: 1

Related Questions