RowFilter on a DataTable to display in a gridview
Asked Answered
N

2

5

I have the following code which doesn't seem to work. In the Page_Load function I populate the DataSet and display the results in a grid view.

newsCommand = new SqlCommand("SQL code here", dbConnection);
newsDataSet = new DataSet();
newsDataAdapter = new SqlDataAdapter(newsCommand);
newsDataAdapter.SelectCommand = newsCommand;
newsDataAdapter.Fill(newsDataSet, "Bulletins");

if (!Page.IsPostBack)
{
    GridViewMain.DataSource = newsDataSet;
    GridViewMain.DataBind();
}

I have some links which call this function to filter the data (yearID is passed as a parameter):

DataTable newsTable = new DataTable();
newsTable = newsDataSet.Tables[0];

DataView dvData = new DataView(newsTable);
dvData.RowFilter = "Year > '" +  yearID + "'";

GridViewMain.DataSource = dvData;
GridViewMain.DataBind();

Yet the gridview shows the data it orignally loaded, and not the filtered data. The only thing I can think of is that I'm not using the DataTable in the Page_Load function. What else am I missing?

Thanks,

Adrian

Neoplasty answered 10/8, 2010 at 14:20 Comment(3)
DataTable newsTable = newsDataSet.Tables[0], please.Homocyclic
yearID is a parameter which started as a year value to filter data by, but I amended it to a full date. I've just changed the code in the function to: newsDataSet.Tables[0].DefaultView.RowFilter = "NewsDate2 > '01/01/2010'"; GridViewMain.DataSource = newsDataSet.Tables[0].DefaultView; GridViewMain.DataBind(); but it still does the same thing (not filtering the data).Neoplasty
Just realised the comments box doesn't format code (am new to SO, and have only just returned to ASP, which is why my code might seem a little incorrect).Neoplasty
N
7

Changed the code in the function to:

DataView dataView = newsDataSet.Tables[0].DefaultView;
dataView.RowFilter = "NewsDate2 Like '%" + yearID + "'";

GridViewMain.DataSource = dataView;
GridViewMain.DataBind();

It must have been something in the RowFilter statement.

Neoplasty answered 10/8, 2010 at 15:6 Comment(0)
E
0

Filter data from DataTable and display it in Gridview.

        string category = ddlcat.SelectedItem.Value; // this can be any input by user
        DataTable dt = filter_dt; //filter_dt is DataTable object, contains actual data, from there we will filter
        DataView dataView = dt.DefaultView;
        if (!string.IsNullOrEmpty(category))
        {
            dataView.RowFilter = "Category = '" + category + "'";
        }
        Gridview1.DataSource = dataView;
        Gridview1.DataBind();

If any doubt,feel free to ask.

Thank you

Enrollee answered 12/12, 2019 at 5:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.