SQL Datareader无法将数据绑定到GridView

时间:2015-04-17 07:29:06

标签: c# asp.net sql-server grid

protected void Button1_Click(object sender, EventArgs e)
{
    string query = "select * from aspnet_Users where userName like '%@UserName%'";
    connection.Open();
    SqlCommand command = new SqlCommand(query, connection);
    command.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = TextBox1.Text;
    SqlDataReader reader = command.ExecuteReader();
    GridView1.DataSource = reader;
    GridView1.DataBind();
    connection.Close();
}

我正在尝试使用连接模型在表中搜索用户的数据,但GridView总是从不填充数据。

2 个答案:

答案 0 :(得分:1)

您的参数在查询中充当字符串,因为您在参数周围包含了单引号。这就是它无法识别参数的原因。试试这个: -

string query = "select * from aspnet_Users where userName LIKE @UserName";

然后将其添加为如下参数: -

command.Parameters.Add("@MyName",SqlDBType.NVarChar,40).Value ="%" + TextBox1.Text + "%";

答案 1 :(得分:0)

您可以使用SqlDataAdapter填充gridview,您的代码如下所示

        string query = "select * from aspnet_Users where userName like '%@UserName%'";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = query;
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@UserName", TextBox1.Text);
        cmd.Connection = conn;
        SqlDataAdapter dap = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        dap.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
       GridView1.DataBind();