CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

  1. #1
    Join Date
    Nov 2004
    Posts
    12

    Sorting By Multiple Columns How Can i Do i?

    I have some problem with sorting in multiple columns. I tried duplicating the the events etc but it still won't work. It tends to only sort by one expression. For example, i have 2 columns "name" and "company". When i click name, it will sort in ascending order of the names, which is correct but when i tried sorting by company, it sorts by name which isn't correct.

    The code below is for sorting only by name.
    Code:
    private void Page_Load(object sender, System.EventArgs e)
    {
    	if (!Page.IsPostBack) 
    	{ 
    	                ViewState["sortField"] = "Name";
    	                ViewState["sortDirection"] = "DESC";
    		BindGrid();
    	}
    }
    
    private void BindGrid()
    {
                    SqlCommand cmd = sqlConnection1.CreateCommand();
    	cmd.CommandText = "SELECT * FROM Factory.Company ORDER BY " + ViewState["sortField"].ToString() + " " + ViewState["sortDirection"].ToString();
    	SqlDataAdapter sqlDataAdapter11 = new SqlDataAdapter();
    	sqlDataAdapter11.SelectCommand = cmd;
    	DataSet ds = new DataSet();
    	sqlConnection1.Open();
    	sqlDataAdapter11.Fill(ds, "Company");
    	sqlConnection1.Close();
    	DataGrid5.DataSource = ds;
    	DataGrid5.DataBind();
    }
    private void DataGrid5_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
    	DataGrid5.CurrentPageIndex = e.NewPageIndex;
    	BindGrid();
    }
    
    private void DataGrid5_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
                    if(e.SortExpression.ToString() == ViewState["sortField"].ToString())
    	{
    		switch(ViewState["sortDirection"].ToString())       
    		{         
    			case "ASC":   
    			ViewState["sortDirection"] = "DESC";
    			break;
    
    			case "DESC":            
    			ViewState["sortDirection"] = "ASC";
    			break;
    		}
    	}
    	else
    	{
    		ViewState["sortField"] = e.SortExpression;
    		ViewState["sortDirection"] = "DESC";
    	}
    		BindGrid();
    	}
    What should be added in order to make multi column sorting work? or i have to re-write the whole program?

    Help needed thanks in advance

    -John
    Last edited by Eradicate; November 30th, 2004 at 04:47 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured