0
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.

7
  • Did you tell the reader to read??Try calling reader.Read() Commented Apr 17, 2015 at 7:31
  • change your LIKE to like '%' + @UserName+ '%'" Commented Apr 17, 2015 at 7:32
  • @ughai, that doesnt make sense. Commented Apr 17, 2015 at 7:33
  • @serv - '%@UserName%' will be taken as a literal comparison and the value of the parameter will not be replaced. Commented Apr 17, 2015 at 7:35
  • check the value of the 1st column DECLARE @UserName VARCHAR(10) ='hi' SELECT'%@UserName%' ,'%' +@UserName + '%' Commented Apr 17, 2015 at 7:37

2 Answers 2

1

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 + "%";
Sign up to request clarification or add additional context in comments.

2 Comments

@ÃhmëdSäßrý - What is the error message you are getting?
@ÃhmëdSäßrý - Have you debugged the code? Are you getting any data. Please debug and check if you hitting the correct DB and if you are getting the records.
0

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();

2 Comments

I don't recommend using disconnected model with asp.net because it may cause a bottleneck problems.
But though, I tried it and there is exception 'Cannot find table 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.