Datarow.Delete() command by unknown Row index

Asked

Viewed 231 times

1

To remove the Row of a dataGridView using DataTable I can use the command DataRow.Delete() but, for example, in the code below it excludes a Row already known, and in case I need to remove the Row that I am selecting with the mouse click on dataGridView.

I thought maybe remove by index, because each line created has a index (as far as I understand), so if in the selection I manage to catch the index I can delete the line from the DataTable and of dataGridView.

If anyone can help me how to catch the index of the selected line I thank you very much.

     <//Código exemplo
     for (int i = dt.Rows.Count - 1; i >= 0; i--)
    {
        DataRow dr = dt.Rows[i];
        if (dr["name"] == "Joe")
            dr.Delete();
    }>

    DataTable dt = new DataTable("Cadastro");

     <
     //botão para salvar o que eu digitei nas text box (informa o nome e o email do usuario na textbox e mostra no dataGridView)
     private void bt_salvar_Click_1(object sender, EventArgs e)
{


    Pessoa dados = new Pessoa(txt_nome.Text, txt_email.Text);
    DataRow dr = dt.NewRow();

    dr["Nome"] = dados.Nome;
    dr["Email"] = dados.Email;


    dt.Rows.Add(dr);
    dataGridView1.DataSource = dt;


}>

Note: I am not using database and the application is in Winforms.

1 answer

1


The DataGridView has the property CurrentCell who owns the property RowIndex, that returns the index of the cell row that is active/selected.

To use just do the following:

int indexDaLinhaSelecionada = datagridview1.CurrentCell.RowIndex;
  • I ended up being able to delete the line using this: foreach (Datagridviewrow item in this.dataGridView1.Selectedrows) { dataGridView1.Rows.Removeat(item.Index); } dataGridView1.Update(); dataGridView1.Refresh();

  • Got it. That’s how it works too, but you don’t think it’s better to call the property straight instead of iterating a loop?

  • 1

    Yes, of course. And thank you very much for your help, I will use this form!

Browser other questions tagged

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