Reputation: 259
I am a new ASP.NET Web Forms developer and I am struggling now in with the best way of filtering the data by the value of QueryString before binding it to the GridView control. I am binding the GridView to the GetData() method, and I would like to filter the data in the code-behind based on the value of the QueryString if there is a QueryString. So should I do the checking of the QueryString in the BindGrid() method or in the Page_Load() method? And how should I do it?
For your information, the GridView has a pagination capability as shown in the code-behind below.
Here's the C# code for the GetData():
public IEnumerable<Item> getData(Item itemObj)
{
List<Item> itemList = new List<Item>();
using (ATMSEntities context = new ATMSEntities())
{
itemList = (from item in context.Item
select new Item()
{
ItemId = item.ItemId,
Name = item.Name,
}).ToList();
if (itemObj.ItemId != 0)
{
itemList = itemList.Where(item => item.ItemId == itemObj.ItemId).ToList();
}
}
}
return itemList;
}
And here's the code-behind for the aspx page that has the GridView control:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["ItemId"] != null) //the filtration is not working here.
{
bindGrid();
}
}
private void bindGrid()
{
Item itemObj = new Item();
var result = itemObj.getData(itemObj).ToList();
gvItems.DataSource = itemObj.getData(itemObj);
gvItems.DataBind();
}
protected void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvItems.PageIndex = e.NewPageIndex;
bindGrid();
}
Thanks in advance for your help.
Upvotes: 0
Views: 1098
Reputation: 5771
You are not using the QueryString value to filter the list items. What you should be doing is this
private void bindGrid()
{
Item itemObj = new Item();
if(Request.QueryString["ItemId"] != null)
{
itemObj.ItemId = Convert.ToInt32(Request.QueryString["ItemId"]);
}
var result = itemObj.getData(itemObj).ToList();
gvItems.DataSource = itemObj.getData(itemObj);
gvItems.DataBind();
}
Upvotes: 1