DataGridView's row headers lose their captions on sort

1k Views Asked by At

I followed a tip in here which said:

datagridview1.Rows[0].HeaderCell.Value = "ur text";

With help of this I set up a method:

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e, DataSet src)
{
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        dataGridView1.Rows[i].HeaderCell.Value = row_captions[i];
    }
}

and it nicely fills all my rows' headers with captions. The problem occurs when I try to sort any column. This method is called again and the captions stay in the same order even tho the rows are arranged in a different way. I tried using a bool value so it wouldn't call this method again like this:

private first_time = true;

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e, DataSet src)
{
    if(first_time)
    {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            dataGridView1.Rows[i].HeaderCell.Value = row_captions[i];
        }
    }
}

private void dataGridView1_Sorted(object sender, EventArgs e)
{
    first_time = false;
}

However now, it won't add the captions at all, because apparently the rows are removed and added again and thus lose their properties (correct me if I am wrong, because I am not completely sure).

Is there a way to both: maintain the captions of the rows and sort them accordingly?

1

There are 1 best solutions below

3
spajce On BEST ANSWER

i tried to set the HeaderCell.Value in the event CellFormatting and its sort accordingly

 private void dataGridView`_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 1)
        {
            dataGridView1.Rows[e.RowIndex].HeaderCell.Value = e.Value;
        }
    }