Search code examples
c#winformsdatagridviewalignmentcell

DataGridView align one specific Cell


Is it possible to align one single specified cell in c# dataGridView?

The idea would be something like this (but without errors)

tT.Rows[j][1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight; 

Solution

  • Is it possible to align one single specified cell in DataGridView?

    Yes, this is quite easy. Either pick the Cell and set the Style:

    DataGridViewCell dc = dataGridView1[0, 0];   // short reference
    dc.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    

    Or code the CellPainting event to conditionally align Cells:

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if ((e.RowIndex >= 0) && (e.ColumnIndex >= 0))
        {
            if (e.Value != null && e.Value.ToString() == "ddd")
            {
                e.CellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
            }
        }
    }
    

    Coding suitable conditions is up to you, of course.

    enter image description here

    Note that after reloading the rows the alignment from the 1st option will be gone; the 2nd way will still align those cells that fit the conditions..