Link to home
Start Free TrialLog in
Avatar of KCTechNet
KCTechNetFlag for United States of America

asked on

Setting FilterExpression on GridView component at runtime in C#

Hello,
I have an application that queries an SQL table for a list of patients. The results of this query are displayed on a GridView component. I have the component coded to populate with patients information at runtime.  I am not sure how to programmatically set the filter expression for any of the columns.  (I can set FilterExpression within aspx but this is not an option for the application and I need to have FilterExpression set/configured at runtime.  Is this possible in C#?

Thank you!

Here is my method:
// I would like to filter the query results based on text entered in a component called Label1.Text to filter [clientLast]
 protected void BindGrid()
        {
            DataTable dt = new DataTable();
            SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["PEIGenericConnectionString"].ConnectionString);
            string strSelect = @"SELECT [clientFirst] AS 'First Name', [clientMI] AS 'MI', [clientLast] AS 'Last Name', CONVERT(VARCHAR, [dob], 111) AS 'DOB' FROM [Individual_Client] WHERE [programNameID] = @programNameID";

            SqlCommand cmd = new SqlCommand(strSelect, connection);
            connection.Open();

            cmd.Parameters.Add("@programNameID", SqlDbType.Int, 2);
            cmd.Parameters["@programNameID"].Value = Convert.ToInt32(Request.QueryString["programNameID"]);

            SqlDataAdapter ad = new SqlDataAdapter(cmd);

            ad.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            else
                return;  
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ark
Ark
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KCTechNet

ASKER

Hi Ark,
I tried setting my dv.RowFilter property but the gridview component isn't showing up at all.  I might be missing something altogether that I will need to figure out on my own.  Logically, should dv.RowFilter be assigned my filter AFTER DataBind()?  
Thanks for your reply!
try DataView dv = dt.DefaultView;
also check you filter expression. Note it should be like sql WHERE clause, ie string parameters, for example, must be in quotes