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.
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();
– Bellon
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?
– igventurelli
Yes, of course. And thank you very much for your help, I will use this form!
– Bellon