CodeGo.net>如何删除一个选定的DataGridViewRow和更新连接的数据库表?

我在Windows Forms应用程序(用C#编写)上有DataGridView控件。

我需要的是:当用户选择DataGridViewRow,然后单击“删除”按钮时,应删除该行,然后,需要使用表适配器更新数据库。

这是我到目前为止的内容:

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

此外,这仅删除一行。 我希望用户可以在其中选择多行。

Woody asked 2020-06-29T20:19:10Z
14个解决方案
70 votes

此代码删除dataGridView1的选定项目:

 private void btnDelete_Click(object sender, EventArgs e)
 {
     foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
     {
         dataGridView1.Rows.RemoveAt(item.Index);
     }
 }
Navid Farhadi answered 2020-06-29T20:19:18Z
21 votes
private void buttonRemove_Click(object sender, EventArgs e)
{
    foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
    {
        if (oneCell.Selected)
            dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
    }
}

删除索引位于选定单元格中的行。 因此,选择任何单元格,它们对应的行将被删除。

Filip answered 2020-06-29T20:19:38Z
10 votes

我已经编写了以下代码,请看一下:

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

使用所选行的Index仍然可以工作; 看看下面的代码是否可以解决问题:

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

希望这对您有所帮助。

serge_gubenko answered 2020-06-29T20:20:07Z
4 votes
private void btnDelete_Click(object sender, EventArgs e)
{
    if (e.ColumIndex == 10)// 10th column the button
    {
        dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
    }                
}

该解决方案可以通过“ e”参数删除一行(未选中,单击行!)。

huncyrus answered 2020-06-29T20:20:27Z
1 votes

要删除datagrid中的多行,c#

我的部分代码:

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

        }
littlecodefarmer758 answered 2020-06-29T20:20:51Z
1 votes
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());
    }
}
techydesigner answered 2020-06-29T20:21:06Z
1 votes

好吧,这就是我通常如何从DataGridView中删除用户所检查的行,如果您将其与Dataset中的数据表相关联(例如:DataGridView1.DataSource = Dataset1.Tables["x"]),那么一旦您将在其中进行任何更新(删除,插入,更新) Dataset,它将自动在您的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);
            }
        }
Sarah Chaygani answered 2020-06-29T20:21:27Z
0 votes

看看这种方式:

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);
 }
Sarvar Nishonboev answered 2020-06-29T20:21:46Z
0 votes

试试这个:

if (dgv.SelectedRows.Count>0)
{
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
Sherif Hamdy answered 2020-06-29T20:22:06Z
0 votes
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();
    }
}
Mohammad Saqib answered 2020-06-29T20:22:21Z
0 votes

您首先从数据库中删除,然后更新datagridview

//let's suppose delete(id) is a method which will delete a row from the database and
// returns true when it is done
int id = 0;
//we suppose that the first column in the datagridview is the ID of the ROW :
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
   id = Convert.ToInt32(row.Cells[0].Value.ToString());
if(delete(id))                               
   this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//else show message error!
Z.D.E Informaticien answered 2020-06-29T20:22:41Z
0 votes
private void btnDelete_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                ?BindingSource.EndEdit();
                ?TableAdapter.Update(this.?DataSet.yourTableName);
}

//NOTE:
//? - is your data from database

不需要例外...或使用您自己的代码进行更改。

码:enter image description here

D B:enter image description here

示例:prntscr.com/p3208c

数据库集:[http://prntscr.com/p321pw]

Grofman answered 2020-06-29T20:23:18Z
-1 votes
for (int j = dataGridView1.Rows.Count; j > 0 ; j--)
{
    if (dataGridView1.Rows[j-1].Selected)
        dataGridView1.Rows.RemoveAt(j-1);
}
Pavan Muppalla answered 2020-06-29T20:23:34Z
-3 votes

这是一个非常简单的示例:

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"/>

背后的代码:

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

您将必须使用复选框或其他某种机制来允许用户选择多个行,然后您可以浏览已选中复选框的行,然后删除这些行。

TheVillageIdiot answered 2020-06-29T20:24:07Z
translate from https://stackoverflow.com:/questions/2084346/how-to-delete-a-selected-datagridviewrow-and-update-a-connected-database-table