0

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.

4

2 回答 2

5

您不能自动将变量绑定到您的命令。您需要手动执行此操作,例如:

using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM TEST_TABLE WHERE ID = @filter", conn))
{
    int filter = ID;
    a.SelectCommand.Parameters.AddWithValue("@filter", filter);
于 2013-06-18T15:52:45.403 回答
1
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; 
        }
于 2013-06-18T15:53:05.477 回答