Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Form: change dataGridView's first cell origin?

Long story short, I have this dataGridView and I want the cell [0,0] to be the cell on the lower-left corner of the grid, not on the top-left of the grid like it does by default.

For example, visually, if i do something like:

dataGridView1[0, 0].Value = "a";

I get this (sorry not enough reputation to post pictures)

but I'd like "a" to appear, by doing the same instruction, at the blue highlighted slot, and by doing stuff like adding a row it would be added on the top of the grid.

Many thanks in advance and regards

like image 945
Asduffo Avatar asked Jun 11 '15 15:06

Asduffo


2 Answers

Create one class like this:

public class MyDataGridView : DataGridView
{
    public new DataGridViewCell this[int col, int invertRow]
    {
        get
        {
            int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1);
            return this.Rows[recordCount - invertRow].Cells[col];
        }
        set
        {
            int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1);
            this.Rows[recordCount - invertRow].Cells[col] = value;
        }
    }
}

and call that like this:

dataGridView1[0, 0].Value = "a";

or if you want set or get first cell in top-left of grid only then you can use FirstDisplayedCell property.

MSDN: Gets or sets the first cell currently displayed in the DataGridView; typically, this cell is in the upper left corner.

For example:

dataGridView1.FirstDisplayedCell.Value = "a";
like image 140
Behzad Avatar answered Sep 26 '22 14:09

Behzad


There's no native way to do what you want without extending the class, but you can use extension methods that will invert the row index for you:

public static DataGridViewCell FromLowerLeft(this DataGridView dgv, int columnIndex, int invertedRowIndex)
{
    return dgv[columnIndex, dgv.RowCount - invertedRowIndex];
} 

This can be used as

dataGridView.FromLowerLeft(0,0).Value = "a";
like image 24
Rubixus Avatar answered Sep 23 '22 14:09

Rubixus