Click here to Skip to main content
15,917,862 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

i have unbound datagridview and i added autonumber in rows header.
I also added autonumber in first column cells but lets focus just on rows header.
Problem is when i sort the grid by values from some column the numbers in rows header lose order.
To be precise i want to have 1,2,3,4,5...ALWAYS in row header in that order,no mather what sorting i am doing on the grid.
Tried to find solution by changing again the row headers in grids events 'Sorted' and 'SortCompare' but with no luck.
Here is my code where on Initialisation i am adding some names from the list and autonumbers in first two columns and adding autonumbers to row header.

C#
public Form3(List<string>; list, int brojkola)
{
   InitializeComponent();
   this.WindowState = FormWindowState.Maximized;

   dodajkolone(brojkola);

   foreach (string igrac in list)
   {
      this.dataGridView1.Rows.Add();
      this.dataGridView1.Rows[list.IndexOf(igrac)].Cells[1].Value = igrac;
      int rednibroj = list.IndexOf(igrac);
      this.dataGridView1.Rows[rednibroj].Cells[0].Value = rednibroj + 1;
      setRowNumber(dataGridView1);
   }

   dataGridView1.Refresh();
}

private void setRowNumber(DataGridView dgv)
{
   int broj = 1;
   foreach (DataGridViewRow r in dgv.Rows)
   {
      r.HeaderCell.Value = (broj).ToString();
      //dgv.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
      broj++;
   }
}


Is there any way to prevent first column to be sorted when user sort on some other column or to prevent rows header to be sorted and stay always like autonumber 1,2,3,4...or is there any way after sorting by a column to put some code in some event to display numbers in row header in order i want.What event i should use for that.
Posted
Updated 18-Apr-15 12:16pm
v2

If you always want the same numbers in your how headers, that's pretty easy.
So if you want:
1  AAA
2  AAB
3  BAA
4  CAA
And
VB
1  CAA
2  BAA
3  AAB
4  AAA
Then just handle the Sorted event for the DGV:
C#
private void myDataGridView_Sorted(object sender, EventArgs e)
    {
    DataGridView dgv = sender as DataGridView;
    if (dgv != null)
        {
        ReNumberRows(dgv);
        }
    }

private void ReNumberRows(DataGridView dgv)
    {
    int i = 0;
    foreach (DataGridViewRow row in dgv.Rows)
        {
        row.HeaderCell.Value = (++i).ToString();
        }
    }
 
Share this answer
 
Thank you so much!

As i already say :"Tried to find solution by changing again the row headers in grids events 'Sorted' and 'SortCompare' but with no luck."

tried to reorder rows header in the datagreedview Sorted event but i guess i did something wrong.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900