Reputation: 53
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();
}
I am trying to use connected model to search a user's data in a table but the GridView is always, never fills with data.
Upvotes: 0
Views: 300
Reputation: 10218
You can populate gridview using SqlDataAdapter
, your code look like this
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();
Upvotes: 0
Reputation: 21825
You parameter is acting as a string in your query because of single quotes you have include around the parameter. That is the reason it is not able to identify the parameter. Try this:-
string query = "select * from aspnet_Users where userName LIKE @UserName";
Then add it as parameter like this:-
command.Parameters.Add("@MyName",SqlDBType.NVarChar,40).Value ="%" + TextBox1.Text + "%";
Upvotes: 1