Friday, May 30, 2008

Webcontrol GridView with sorting

For everyone with the error:

The GridView "dgGridView" fired event Sorting which wasn't handled.

Here is the solution:

If you get the above error your allready set the AllowSorting="true" if not set it to your gridView.
Add to the grid an method for the event "sorting", when double click in the properties list it will create a new method for you which looks like this:


protected void gvProjectParts_Sorting(object sender, GridViewSortEventArgs e)
{
}


First we bind the data from SQL and put the datatable in the ViewState because we need this later.


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet dataset = new DataSet();
SqlConnection conn = new SqlConnection("ConnectionString");
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("select * from tblTable", conn);
adapter.Fill(dataset);
DataTable table = dataset.Tables[0];
if (table.Rows.Count > 0)
{
gvProjectParts.DataSource = table;
ViewState["gvProjectParts_DataSource"] = table;
gvProjectParts.DataBind();
}
}
}


Then we adjust the sort method where we use the saved viewstate, this is because gvProjectParts.DataSource and send.DataSource are empty:

protected void gvProjectParts_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable m_DataTable = (DataTable)ViewState["gvProjectParts_DataSource"];
if (m_DataTable != null)
{
DataView m_DataView = new DataView(m_DataTable);
m_DataView.Sort = e.SortExpression + " " + getSortDirection();
(sender as GridView).DataSource = m_DataView;
(sender as GridView).DataBind();
}
}

The function getSortDirection is explained here where we use the ViewState again to store the direction. This is because e.SortDirection is allways ASC.


private string getSortDirection()
{
string m_SortDirection;
if (ViewState["gvProjectParts_sortDirection"] == null)
m_SortDirection = "DESC";
else
m_SortDirection = (string)ViewState["gvProjectParts_sortDirection"];
switch (m_SortDirection)
{
case "ASC":
m_SortDirection = "DESC";
break;
case "DESC":
m_SortDirection = "ASC";
break;
}
ViewState["gvProjectParts_sortDirection"] = m_SortDirection;
return m_SortDirection;
}


Try it out !

Big thanks to Ryan Olshan and his post

Think it can also be done without using ViewState, please tell me how :)

Cheers,
Sjoerd

No comments: