ASP.NET GridView.DataBind does not update GridView

To get started, I use the MultiView control to navigate users through the search. The first page in MultiView is just a search box with a button for a preliminary search.

The second page has a GridView, but I would like to save the search box and a button to search for the user again if they did not find the user they were looking for.

When you search from page 1 and go to page 2, the GridView shows the correct results. But when it is on the second page with GridView and search, GridView is not updated. 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; } } 
+4
source share
2 answers

Do you need to set the DataSource property? You have this in the comments above the code, but it is not clear when this happens. Place a breakpoint on SearchResults.DataBind () and make sure all properties are set here correctly.

By the way, these problems arise because it is infinitely preferable to use the proper level of business logic. If you control the code that actually executes the database query, you will 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: Everything works as you expect if you remove MultiView? Let me narrow the problem.

+3
source

Instead of declaring a new gridview "SearchResults", and then causing the data to bind to a shadow copy of your gridview, just bind the gridview in the view itself.

Just call

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

instead

SearchResults.DataBind();

Then you can get rid of

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

That way, your SqlDataSource control will do select () when binding data to an existing gridview, not a copy.

0
source

Source: https://habr.com/ru/post/1301168/


All Articles