How to arrange the FieldName in AspxGridView?

176 views Asked by At

I want to arrange the Field Names as user wants to display. I am not using SqlDataSource. I am calling the stored procedure by programming like below.

string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;

using (SqlConnection con = new SqlConnection(cs))
{
   SqlCommand cmd = new SqlCommand("spGetTotalSalesQuantity",con);
   cmd.CommandType = System.Data.CommandType.StoredProcedure;
   cmd.Parameters.AddWithValue("@DateFrom", DateFromStr);
   cmd.Parameters.AddWithValue("@DateTo", DateToStr);
   //cmd.Parameters.AddWithValue("@DateFrom", "2015-01-01 00:00:00");
   //cmd.Parameters.AddWithValue("@DateTo", "2015-12-31 23:59:59");

   con.Open();

   SqlDataAdapter sda = new SqlDataAdapter(cmd);
   sda.Fill(ds);

   ASPxGridView1.DataSource = ds;
   ASPxGridView1.DataBind();
}

In result, I can see the field name how i have given the Column_name in my query. But, User wants to see the Field Name how they are arranging.

For Example:

select 
    student_id,student_name ,Class,School_Name
From
    Student_Details

If above one is my stored procedure. I will get the Field Name how I mentioned in my query.

But User wants to see the result how they are giving. If user give School_Name,Class,Student_id,School_Name.

Is there anyway to arrange in AspxGridView?

2

There are 2 answers

0
AudioBubble On BEST ANSWER
  1. Use the hiddentext field and get the column names as user wants to display in which order.

    string selectedColumns = HiddentxtSelectedColumn.Value;

  2. Move the selectedColumns to array

    string[] names = selectedColumns.Split(',');
    sda.Fill(ds);
    
    for (int i = 0; i < names.Length; i++)
    {
        ds.Tables[0].Columns[names[i]].SetOrdinal(i);`
    }
    
    ASPxGridView1.DataSource = ds;
    ASPxGridView1.DataBind();
    

Now It will run exactly.

1
shreesha On

Check my answer Based on my understanding of the question and @mohamed's comment.

Try to use the DataColumn.SetOrdinal method. For example:

con.Open();

   SqlDataAdapter sda = new SqlDataAdapter(cmd);
   sda.Fill(ds);

   ds.Tables[0].Columns["School_Name"].SetOrdinal(0);
   ds.Tables[0].Columns["Class"].SetOrdinal(1); 
   ds.Tables[0].Columns["Student_id"].SetOrdinal(2);
   ds.Tables[0].Columns["School_Name"].SetOrdinal(3); 

   ASPxGridView1.DataSource = ds;
   ASPxGridView1.DataBind();

even if user changes the select statement order of columns will not change.