Question

I have a text box named recordID I have declared a variable called ID by using the following:

int ID = Convert.ToInt32(recordID.Text);

Finally, I have some code which refreshes a gridview after a button has been clicked which works perfectly, but, brings back everything in the table:

        using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM TEST_TABLE", conn))
        {

            // Use DataAdapter to fill DataTable
            DataTable t = new DataTable();
            a.Fill(t);

            // Render data onto the screen
            gridSelectID.DataSource = t; 
        }

I need this to be altered wherby the query is changed so that it adds a where and filters it on the value of the ID mentioned above (taken from recordID.Text which is a text box)

I have tried this:

        using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM TEST_TABLE WHERE ID = filter", conn))
        {
            int filter = ID;
            // Use DataAdapter to fill DataTable
            DataTable t = new DataTable();
            a.Fill(t);

            // Render data onto the screen
            gridSelectID.DataSource = t; 
        }

But it complains with Invalid Column name 'filter' I need this to filter the query by the ID which is declared at the top of the code.

Was it helpful?

Solution

You can't automatically bind variables to your command. You need to do it manually, like:

using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM TEST_TABLE WHERE ID = @filter", conn))
{
    int filter = ID;
    a.SelectCommand.Parameters.AddWithValue("@filter", filter);

OTHER TIPS

using (SqlDataAdapter a = new SqlDataAdapter(string.Format("SELECT * FROM TEST_TABLE WHERE ID = '{0}'",ID), conn))            {

            // Use DataAdapter to fill DataTable
            DataTable t = new DataTable();
            a.Fill(t);

            // Render data onto the screen
            gridSelectID.DataSource = t; 
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top