简体   繁体   中英

ASP.NET GridView.DataBind not refreshing the GridView

To start I am using a MultiView control to step users through searching. The first page in the MultiView is just a search box with a button to preform the search.

The second page has the GridView, but I would like to keep the search box and button for the user to search again if they didn't find the user they were looking for.

When you search from page one and move to page 2 the GridView shows the correct results. But when it is on the second page with both the GridView and the search the GridView doesn't update. Below is the code I'm using.

//GridView = SearchResults  
//SqlDataSource = AddPlayerDataSource  
//MultiView = PlayerSearchView

protected void PlayerSearch_Click(object sender, ImageClickEventArgs e)
{
    string userId = User.Identity.Name.ToString();

    if (SearchText.Text != "" && !userId.Equals(""))
    {
        GridView SearchResults = (GridView)PlayerSearchView.FindControl("SearchResults");

        string SqlSelect = "SELECT [id], [username] FROM [users] WHERE [username] LIKE '%" + SearchText.Text + "%'";
        AddPlayerDataSource.SelectCommand = SqlSelect;
        SearchResults.DataBind();

         if (PlayerSearchView.ActiveViewIndex != 1)
             PlayerSearchView.ActiveViewIndex = 1;
    }
}

Do you need to set the DataSource property? You have that set in comments above the code, but it's unclear when that is happening. Put a breakpoint on SearchResults.DataBind() and make sure all the properties are set correctly here.

Incidentally... these kinds of problems are why it's infinitely preferable to use a proper business logic layer. If you were controlling the code that actually does the DB query you'd either not have this problem or know exactly where it was.

GridView SearchResults = (GridView)PlayerSearchView.FindControl("SearchResults");
SearchResults.DataSource = Data.Players.LoadAll(); //Loads a DataTable with your data
SearchResults.DataBind();

EDIT: Does everything work the way you expect it to if you remove the MultiView? Let's narrow down the problem.

Instead of declaring a new gridview "SearchResults" and then calling databind on that shadow copy of your gridview, just databind the gridview in the view itself.

Just call

((GridView)PlayerSearchView.FindControl("SearchResults")).DataBind()

instead of

SearchResults.DataBind();

Then you can get rid of

GridView SearchResults = (GridView)PlayerSearchView.FindControl("SearchResults");

That way your SqlDataSource control will execute the select() when databinding the existing gridview, not the copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM