Visual Studio .NET - Dynamically added girdview sorting

Asked By shekhar kumar on 01-Oct-08 05:05 AM
I have create a gridview on runtime like follows GridView G1 = new GridView(); G1.AutoGenerateColumns = false; G1.AllowSorting = true; BoundField BF1 = new BoundField(); BF1.DataField = "Employee_ID"; BF1.HeaderText = "Employee ID"; G1.Columns.Add(BF1); BoundField BF2 = new BoundField(); F2.DataField = "EmployeeID"; BF2.HeaderText = "Name"; G1.Columns.Add(BF2); BoundField BF3 = new BoundField(); BF3.DataField = "ManagerID"; BF3.HeaderText = "Manager"; G1.Columns.Add(BF3); SqlDataAdapter da = new SqlDataAdapter("Select * from Employees","Data source=srvisaparam;user id=sa; initial catalog=shekhar;"); DataSet ds = new DataSet(); da.Fill(ds); G1.DataSource = ds; G1.DataBind(); Now I want the sorting feature in this. But I am not able to do that. Thanks

sorting event - Perry replied to shekhar kumar on 01-Oct-08 05:13 AM

You will need to use Pagging and Sorting concept. Put following line in your code. and use given code.

<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" OnSorting="gridView_Sorting" runat="server" />

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   Response.Write(gridView.DataSource.GetType()); //Add this line

   DataTable m_DataTable = gridView.DataSource as DataTable;

   if (m_DataTable != null)
   {
      DataView m_DataView = new DataView(m_DataTable);
      m_DataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

      gridView.DataSource = m_DataView;
      gridView.DataBind();
   }
}

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

//BindGridControl() is very important and make sure that your datatable is bind to GridView control instead of dataSet

   BindGridControl(); 
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}

Megha

solution using viewstate - Perry replied to shekhar kumar on 01-Oct-08 05:16 AM

You can either use Viewstate to sort gridview items. Refer following code from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx

protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
  {

    //Retrieve the table from the session object.
    DataTable dt = Session["TaskTable"] as DataTable;

    if (dt != null)
    {

      //Sort the data.
      dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
      TaskGridView.DataSource = Session["TaskTable"];
      TaskGridView.DataBind();
    }

  }

  private string GetSortDirection(string column)
  {

    // By default, set the sort direction to ascending.
    string sortDirection = "ASC";

    // Retrieve the last column that was sorted.
    string sortExpression = ViewState["SortExpression"] as string;

    if (sortExpression != null)
    {
      // Check if the same column is being sorted.
      // Otherwise, the default value can be returned.
      if (sortExpression == column)
      {
        string lastDirection = ViewState["SortDirection"] as string;
        if ((lastDirection != null) && (lastDirection == "ASC"))
        {
          sortDirection = "DESC";
        }
      }
    }

Megha

to add pagging and sorting - Perry replied to shekhar kumar on 01-Oct-08 05:18 AM

If you dont know how to add pagging and sorting to your project then see http://www.exforsys.com/tutorials/asp.net-2.0/asp.net-2.0-adding-sorting-and-paging-in-gridview.html

Megha

thnaks - shekhar kumar replied to Perry on 01-Oct-08 05:22 AM
thanks But I have created and added it at runtime so there will be no method like sorting index changing.
thanks - shekhar kumar replied to Perry on 01-Oct-08 05:24 AM
Thanks again, But it is possible only when you add it on design time. What if I have added it on run time by adding control like text boxes.
the situation is like this - shekhar kumar replied to Perry on 01-Oct-08 05:29 AM
GridView G1 = new GridView(); G1.AutoGenerateColumns = false; G1.AllowSorting = true; BoundField BF1 = new BoundField(); BF1.DataField = "Employee_ID"; BF1.HeaderText = "Employee ID"; G1.Columns.Add(BF1); BoundField BF2 = new BoundField(); BF2.DataField = "EmployeeID"; BF2.HeaderText = "Name"; G1.Columns.Add(BF2); BoundField BF3 = new BoundField(); BF3.DataField = "ManagerID"; BF3.HeaderText = "Manager"; G1.Columns.Add(BF3); SqlDataAdapter da = new SqlDataAdapter("Select * from Employees","Data source=srvisaparam;user id=sa; initial catalog=shekhar;"); DataSet ds = new DataSet(); da.Fill(ds); G1.DataSource = ds; G1.DataBind(); form1.Controls.Add(G1);
dynamically add the gridview - Perry replied to shekhar kumar on 01-Oct-08 05:41 AM

You can dynamically add the gridview and use one of above code for sorting and paging. See http://forums.asp.net/t/1020163.aspx

Regards,

Megha

go through this: - Binny ch replied to shekhar kumar on 01-Oct-08 07:05 AM

protected void OnSort(object sender, GridViewSortEventArgs e)
{
    // There seems to be a bug in GridView sorting implementation. Value of
    // SortDirection is always set to "Ascending". Now we will have to play
    // little trick here to switch the direction ourselves.
    if (String.Empty != m_strSortExp)
    {
        if (String.Compare(e.SortExpression, m_strSortExp, true) == 0)
        {
            m_SortDirection =
                (m_SortDirection == SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
        }
    }
    ViewState["_Direction_"] = m_SortDirection;
    ViewState["_SortExp_"] = m_strSortExp = e.SortExpression;
    this.bindGridView();
}
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        if (String.Empty != m_strSortExp)
        {
            AddSortImage(e.Row);
        }
    }
}
void AddSortImage(GridViewRow headerRow)
{
    Int32 iCol = GetSortColumnIndex(m_strSortExp);
    if (-1 == iCol)
    {
        return;
    }
    // Create the sorting image based on the sort direction.
    Image sortImage = new Image();
    if (SortDirection.Ascending == m_SortDirection)
    {
        sortImage.ImageUrl = "~/dwn.gif";
        sortImage.AlternateText = "Ascending Order";
    }
    else
    {
        sortImage.ImageUrl = "~/up.gif";
        sortImage.AlternateText = "Descending Order";
    }

    // Add the image to the appropriate header cell.
    headerRow.Cells[iCol].Controls.Add(sortImage);
}
go through thses links:

http://www.netomatix.com/development/GridViewSorting.aspx

http://www.exforsys.com/tutorials/asp.net-2.0/asp.net-2.0-adding-sorting-and-paging-in-gridview.html



Go through this, hope it helps: - alice johnson replied to shekhar kumar on 01-Oct-08 08:07 AM

 void SortButton_Click(Object sender, EventArgs e)
  {

    String expression = "";
    SortDirection direction;

    // Create the sort expression from the values selected
    // by the user from the DropDownList controls. Multiple
    // columns can be sorted by creating a sort expression
    // that contains a comma-separated list of field names.
    expression = SortList1.SelectedValue + "," + SortList2.SelectedValue;

    //  Determine the sort direction. The sort direction
    // applies only to the second column sorted.
    switch (DirectionList.SelectedValue)
    {
      case "Ascending":
        direction = SortDirection.Ascending;
        break;
      case "Descending":
        direction = SortDirection.Descending;
        break;
      default:
        direction = SortDirection.Ascending;
        break;
    }

    // Use the Sort method to programmatically sort the GridView
    // control using the sort expression and direction.
    CustomersGridView.Sort(expression, direction);

  }

See this link:

http://www.eggheadcafe.com/tutorials/aspnet/e07f0f1a-4243-4050-8278-00d32b2e5121/aspnet--sorting-a-gridv.aspx

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sort.aspx