Gridview displays old data

M

maggie

hi,
I have a gridview that is based on parameters. When the select statement
does not return any rows, I want to display a label that says 'nothing
found'. It works the first time there is not data, but after that, it
displays what the previous select statement retrieved. How do I fix it so
that it doesn't do that? I am using a datareader. This is my code:
Code:
 cn.Open();
            System.Data.SqlClient.SqlDataReader dr  ;
            dr = cmd.ExecuteReader();
         
            if (dr.HasRows) 
            {
                GridView1.DataSource = dr;
                GridView1.DataBind();
            }
            lblNoData.Visible = (GridView1.Rows.Count == 0);
             
             
            dr.Close();
            cn.Close();
         

       }
 
B

Ben Amada

maggie said:
I have a gridview that is based on parameters. When the select statement
does not return any rows, I want to display a label that says 'nothing
found'. It works the first time there is not data, but after that, it
displays what the previous select statement retrieved. How do I fix it so
that it doesn't do that? I am using a datareader.

Your gridview is retaining the data from the previous time data was bound to
it. To clear this, set the gridview's datasource to null and rebind.

if (dr.HasRows)
{
GridView1.DataSource = dr;
GridView1.DataBind();
} else {
GridView1.DataSource = null;
GridView1.DataBind();
}
 
M

maggie

Thanks Ben. I will try it.

Ben Amada said:
Your gridview is retaining the data from the previous time data was bound to
it. To clear this, set the gridview's datasource to null and rebind.

if (dr.HasRows)
{
GridView1.DataSource = dr;
GridView1.DataBind();
} else {
GridView1.DataSource = null;
GridView1.DataBind();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
DewittMill
Top