How to add a row at the start of the dataGridView C #

1

I'm developing a Tetris game in Windows Forms, I have programmed the movements of all the pieces, I now have to delete the lines that are painted completely.

To remove a line use the code:

dgvTetris.Rows.RemoveAt(27);

As soon as I remove a line, my program should automatically add a line at the beginning, which I can not do.

Follow the initial code for my Tetris:

private void FrmPrincipalTetris_Load(object sender, EventArgs e)
    {

        DataTable DT = new DataTable(); 
        DT.Columns.AddRange(new[]
        {
            new DataColumn("0"), new DataColumn("1"), new DataColumn("2"), new DataColumn("3"), new DataColumn("4"), new DataColumn("5"), new DataColumn("6"), new DataColumn("7"), new DataColumn("8"), new DataColumn("9")
        });
        string[] Espaco = { "", "", "", "", "", "", "", "", "", "" };
        for(int i = 0;i<=27;i++)
        {
            DT.Rows.Add(Espaco);
        }
        dgvTetris.DataSource = DT; // adiciona a matriz no dataGrid
        //dgvTetris.Refresh();
        for(int i=0;i<28;i++)// pinta as celulas de preto
        {
            for(int j=0;j<10;j++)
            {
                dgvTetris.Rows[i].Cells[j].Style.BackColor = Color.Black;
            }
        }

        //dgvTetris.Rows.RemoveAt(27);// remove linha
        //DT.Rows.Add(Espaco);

        //DT.Rows.Add(Espaco);
        //dgvTetris.DataSource = DT;
        //dgvTetris.Rows.RemoveAt(27);
        ///dgvTetris.Refresh();
        // dgvTetris.Rows[27].Delete();
        //dgvTetris.Rows.Remove(dgvTetris.Rows[26]);
        ID_Rotacao = 0;
    }

If someone can help me, all that's missing is for me to finish my project.

Right now, Thank you.

    
asked by anonymous 01.11.2016 / 17:48

1 answer

1

To insert at the beginning use Rows.Insert() , passing the index zero, then the values of the columns:

this.dgvTetris.Rows.Insert(0, "valor coluna 1", "valor coluna 2");

But this would only work if you did not use DataTable

link

In your case, do so:

// crie uma nova linha
DataRow row = DT.NewRow();

// estou adicionando um valor de teste na primeira coluna da linha
row[0] = "teste";

// adicione esse linha na posição zero do DataTable
DT.Rows.InsertAt(row, 0);
    
01.11.2016 / 18:31