I run this event-handler and method to sort my GridView, but it says that GridView is null:
protected void OtherGridView_Sorting(object sender, GridViewSortEvent开发者_开发百科Args e)
{
DataTable dtSortTable = gvMeldingen.DataSource as DataTable;
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
gvMeldingen.DataSource = dvSortedView;
gvMeldingen.DataBind();
}
private string getSortDirectionString(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
if (sortDirection == SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
The error I get: DataTable must be set prior to using DataView.
And this highlighted: dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection)
The DataSource property is lost during roundtrips. That's why DataTable dtSortTable = gvMeldingen.DataSource as DataTable;
is null, and DataView dvSortedView = new DataView(dtSortTable);
is invalid.
When you hit a sort hyperlink on a datagrid, you are triggering a postback from the client to the server. Then ASP.NET constructs the reply page using persisted data like the ViewState and others.
The DataSource property is not part of the persisted state between round trip, that's why its value is lost.
A solution is requery your DataSource as below:
protected void OtherGridView_Sorting(object sender, GridViewSortEventArgs e)
{
var SortExpression = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
gvMeldingen.DataSource = ... // Requery the Data using the new sort expression above
gvMeldingen.DataBind();
}
Another solution is to set the DataSource each time in the Page_Load event (not recommended)
As you are putting a DataView
around the DataTable
, the method will only work the first time (assuming that the data source is a DataTable
from start). The next time the data source is a DataView
, and you can't cast it to DataTable
.
Use the default view of the DataTable
as data source from start, so that the data source is always a DataView
. Then you can get the view from the source, and get the underlying table from that:
DataView view = gvMeldingen.DataSource as DataView;
DataTable dtSortTable = view.Table;
精彩评论