How to add a line at the beginning of dataGridView C#

Asked

Viewed 3,869 times

1

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

To remove a line I 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 am unable to do.

Follow the initial code of 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 anyone can help me, that’s all I need to finish my project.

As of now, Thank you.

  • Already managed to solve?

  • I did it! Thank you very much.

1 answer

2


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

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

But it would only work if you hadn’t used it DataTable

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.