2010-01-18 12 views
38

Tengo un control DataGridView en una aplicación de Windows Forms (escrita con C#).¿Cómo eliminar un DataGridViewRow seleccionado y actualizar una tabla de base de datos conectada?

Lo que necesito es: cuando un usuario selecciona un DataGridViewRow, y luego hace clic en un botón de 'Borrar', la fila debe suprimirse y siguiente, la base de datos necesita ser actualizada usando adaptadores de mesa.

Esto es lo que tengo hasta ahora:

private void btnDelete_Click(object sender, EventArgs e) 
{ 
    if (this.dataGridView1.SelectedRows.Count > 0) 
    { 
     dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index); 
    }     
} 

Además, esto sólo se elimina una fila. Me gustaría que el usuario pueda seleccionar múltiples filas.

Respuesta

55

Este código elimina los elementos seleccionados de dataGridView1:

private void btnDelete_Click(object sender, EventArgs e) 
{ 
    foreach (DataGridViewRow item in this.dataGridView1.SelectedRows) 
    { 
     dataGridView1.Rows.RemoveAt(item.Index); 
    } 
} 
+6

En general, no siempre es seguro estar modificando un objeto relacionado con el objeto que estamos interactuando sobre, también los índices podrían no ser actualizados. – jmnben

+7

Las mejores prácticas indican que se utiliza un bucle for en lugar de un bucle foreach e iterar hacia atrás desde el final. Esto le ayuda a conservar su índice y evitar problemas mientras edita durante sus iteraciones. – Grungondola

+1

@Grungondola usted debe hacer una respuesta separada para este – User

-3

aquí es un ejemplo muy simple:

ASPX:

<asp:GridView ID="gvTest" runat="server" SelectedRowStyle-BackColor="#996633" 
     SelectedRowStyle-ForeColor="Fuchsia"> 
    <Columns> 
     <asp:CommandField ShowSelectButton="True" /> 
     <asp:TemplateField> 
      <ItemTemplate> 
       <%# Container.DataItemIndex + 1 %> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdateClick"/> 

código subyacente:

public partial class _Default : System.Web.UI.Page 
{ 
    private readonly DataTable _dataTable; 

    public _Default() 
    { 
     _dataTable = new DataTable(); 

     _dataTable.Columns.Add("Serial", typeof (int)); 
     _dataTable.Columns.Add("Data", typeof (string)); 

     for (var i = 0; ++i <= 15;) 
     _dataTable.Rows.Add(new object[] {i, "This is row " + i}); 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
      BindData(); 
    } 

    private void BindData() 
    { 
     gvTest.DataSource = _dataTable; 
     gvTest.DataBind(); 
    } 

    protected void btnUpdateClick(object sender, EventArgs e) 
    { 
     if (gvTest.SelectedIndex < 0) return; 

     var r = gvTest.SelectedRow; 

     var i = r.DataItemIndex; 

     //you can get primary key or anyother column vlaue by 
     //accessing r.Cells collection, but for this simple case 
     //we will use index of selected row in database. 
     _dataTable.Rows.RemoveAt(i); 

     //rebind with data 
     BindData(); 

     //clear selection from grid 
     gvTest.SelectedIndex = -1; 
    } 
} 

y Deberá usar casillas de verificación o algún otro mecanismo para permitir que los usuarios seleccionen varias filas y luego puede examinar las filas de las que tengan marcada la casilla de verificación y luego eliminar esas filas.

+0

Estoy usando WinForms ... – Woody

10

He escrito el siguiente código, por favor, eche un vistazo:

foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
    if (!row.IsNewRow) dataGridView1.Rows.Remove(row); 

utilizando el Index de la fila seleccionada todavía podría funcionar; ver si el código siguiente hará el truco:

int selectedCount = dataGridView1.SelectedRows.Count;   
while (selectedCount > 0) 
{ 
    if (!dataGridView1.SelectedRows[0].IsNewRow) 
     dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index); 
    selectedCount--; 
} 

Espero que esto ayude, saludos.

+0

gracias ... el principal problema que estoy teniendo ahora es guardar en la base de datos usando los adaptadores de tabla. – Woody

+0

necesita proporcionar más detalles sobre lo que no funciona para usted; Apuesto a que la mejor respuesta es comenzar una nueva pregunta con un fragmento de código que está causando problemas –

4
private void btnDelete_Click(object sender, EventArgs e) 
{ 
    if (e.ColumIndex == 10)// 10th column the button 
    { 
     dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]); 
    }     
} 

Esta solución se puede eliminar una fila (fila no seleccionada, haga clic en!) A través de "e" param.

+0

¿Por qué no utilizar foreach en su lugar? Refiérase a la respuesta de @Navid Farhadi. –

18
private void buttonRemove_Click(object sender, EventArgs e) 
{ 
    foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells) 
    { 
     if (oneCell.Selected) 
      dataGridView1.Rows.RemoveAt(oneCell.RowIndex); 
    } 
} 

Quita las filas cuyos índices están en celdas seleccionadas. Por lo tanto, seleccione cualquier celda y se eliminarán sus filas correspondientes.

1

Para eliminar varias filas en la cuadrícula de datos, C#

partes de mi código:

private void btnDelete_Click(object sender, EventArgs e) 
    { 
     foreach (DataGridViewRow row in datagrid1.SelectedRows) 
     { 
      //get key 
      int rowId = Convert.ToInt32(row.Cells[0].Value); 

      //avoid updating the last empty row in datagrid 
      if (rowId > 0) 
      { 
       //delete 
       aController.Delete(rowId); 

       //refresh datagrid 
       datagrid1.Rows.RemoveAt(row.Index); 
      } 
     } 
    } 




public void Delete(int rowId) 
     { 
      var toBeDeleted = db.table1.First(c => c.Id == rowId); 
      db.table1.DeleteObject(toBeDeleted); 
      db.SaveChanges(); 

     } 
0

tienen un aspecto de esta manera:

if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) 
{ 
    foreach (DataGridViewRow item in this.dataGridView1.SelectedRows) 
    { 
     bindingSource1.RemoveAt(item.Index); 
    } 
     adapter.Update(ds); 
} 
1

Prueba esto:

if (dgv.SelectedRows.Count>0) 
{ 
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index); 
} 
1

Bueno, así es como normalmente elimino las filas marcadas por el usuario de un DataGridView, si lo está asociando con un DataTable de Dataset (por ejemplo, DataGridView1.DataSource = Dataset1.Tables["x"]), entonces una vez que haga las actualizaciones (eliminar, insertar, actualizar) en el Dataset, sucederá automáticamente en su DataGridView.

if (MessageBox.Show("Are you sure you want to delete this record(s)", "confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes) 
     { 
      try 
      { 
       for (int i = dgv_Championnat.RowCount -1; i > -1; i--) 
       { 
        if (Convert.ToBoolean(dgv_Championnat.Rows[i].Cells[0].Value) == true) 
        { 
         Program.set.Tables["Champ"].Rows[i].Delete(); 
        } 
       } 
       Program.command = new SqlCommandBuilder(Program.AdapterChampionnat); 
       if (Program.AdapterChampionnat.Update(Program.TableChampionnat) > 0) 
       { 
        MessageBox.Show("Well Deleted"); 
       } 
      } 
      catch (SqlException ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 
1
private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e) 
{ 
    String^ constring = L"datasource=localhost;port=3306;username=root;password=password"; 
    MySqlConnection^ conDataBase = gcnew MySqlConnection(constring); 
    conDataBase->Open(); 
    try 
    { 
     if (MessageBox::Show("Sure you wanna delete?", "Warning", MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes) 
     { 
      for each(DataGridViewCell^ oneCell in dataGridView1->SelectedCells) 
      { 
       if (oneCell->Selected) { 
        dataGridView1->Rows->RemoveAt(oneCell->RowIndex); 
        MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory='ORG 6400H'"); 
        cmdDataBase1->ExecuteNonQuery(); 
        //sda->Update(dbdataset); 
       } 
      }   
     } 
    } 
    catch (Exception^ex) 
    { 
     MessageBox::Show(ex->ToString()); 
    } 
} 
0
if(this.dgvpurchase.Rows.Count>1) 
{ 
    if(this.dgvpurchase.CurrentRow.Index<this.dgvpurchase.Rows.Count) 
    { 
     this.txtname.Text = this.dgvpurchase.CurrentRow.Cells[1].Value.ToString(); 
     this.txttype.Text = this.dgvpurchase.CurrentRow.Cells[2].Value.ToString(); 
     this.cbxcode.Text = this.dgvpurchase.CurrentRow.Cells[3].Value.ToString(); 
     this.cbxcompany.Text = this.dgvpurchase.CurrentRow.Cells[4].Value.ToString(); 
     this.dtppurchase.Value = Convert.ToDateTime(this.dgvpurchase.CurrentRow.Cells[5].Value); 
     this.txtprice.Text = this.dgvpurchase.CurrentRow.Cells[6].Value.ToString(); 
     this.txtqty.Text = this.dgvpurchase.CurrentRow.Cells[7].Value.ToString(); 
     this.txttotal.Text = this.dgvpurchase.CurrentRow.Cells[8].Value.ToString(); 
     this.dgvpurchase.Rows.RemoveAt(this.dgvpurchase.CurrentRow.Index); 
     refreshid(); 
    } 
} 
+1

¿Podría explicar su respuesta, solo el código desnudo no es suficiente? –

-1
for (int j = dataGridView1.Rows.Count; j > 0 ; j--) 
{ 
    if (dataGridView1.Rows[j-1].Selected) 
     dataGridView1.Rows.RemoveAt(j-1); 
} 
Cuestiones relacionadas