50

DataGridView在 Windows 窗体应用程序(用 C# 编写)上有一个控件。

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

这是我到目前为止所拥有的:

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

此外,这只会删除一行。我希望用户可以选择多行。

4

19 回答 19

80

此代码删除选定的项目dataGridView1

 private void btnDelete_Click(object sender, EventArgs e)
 {
     foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
     {
         dataGridView1.Rows.RemoveAt(item.Index);
     }
 }
于 2010-01-18T07:33:11.700 回答
22
private void buttonRemove_Click(object sender, EventArgs e)
{
    foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
    {
        if (oneCell.Selected)
            dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
    }
}

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

于 2012-10-17T21:46:43.350 回答
10

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

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

我希望这会有所帮助,问候。

于 2010-01-19T03:00:26.903 回答
4
private void btnDelete_Click(object sender, EventArgs e)
{
    if (e.ColumIndex == 10)// 10th column the button
    {
        dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
    }                
}

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

于 2012-08-21T09:25:58.080 回答
1

要删除数据网格中的多行,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();

        }
于 2012-10-24T07:03:56.207 回答
1

也许您可以使用临时列表进行删除。用于忽略行索引更改

<pre>
private void btnDelete_Click(object sender, EventArgs e)
{
    List<int> wantdel = new List<int>();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if ((bool)row.Cells["Select"].Value == true)
        wantdel.Add(row.Index);
    }

    wantdel.OrderByDescending(y => y).ToList().ForEach(x =>
    {
        dataGridView1.Rows.RemoveAt(x);
    });           
}
</pre>

于 2020-04-21T02:33:10.010 回答
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());
    }
}
于 2016-08-02T08:39:26.980 回答
1

好吧,这就是我通常如何从 a 中删除用户检查的行的方式DataGridView,如果您将其与 a 中的 DataTable 关联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);
            }
        }
于 2016-03-03T14:09:57.720 回答
0

这样看:

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);
 }
于 2014-03-24T12:44:30.927 回答
0

尝试这个:

if (dgv.SelectedRows.Count>0)
{
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
于 2014-10-08T13:33:39.760 回答
0

尝试这个:

foreach (DataGridViewRow item in this.YourGridViewName.SelectedRows)
{
    string ConnectionString = (@"Data Source=DESKTOPQJ1JHRG\SQLEXPRESS;Initial Catalog=smart_movers;Integrated Security=True");

    SqlConnection conn = new SqlConnection(ConnectionString);
    conn.Open();
    SqlCommand cmd = new SqlCommand("DELETE FROM TableName WHERE ColumnName =@Index", conn);
    cmd.Parameters.AddWithValue("@Index", item.Index);
    int i = cmd.ExecuteNonQuery();

    if (i != 0)
    {
        YourGridViewName.Rows.RemoveAt(item.Index);
        MessageBox.Show("Deleted Succefull!", "Great", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else {
        MessageBox.Show("Deleted Failed!", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
于 2020-06-27T05:15:17.800 回答
0
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

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

代码: 在此处输入图像描述

D B: 在此处输入图像描述

示例:prntscr.com/p3208c

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

于 2019-09-06T09:25:07.273 回答
0

您首先从数据库中删除,然后更新您的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!
于 2019-02-17T16:08:22.620 回答
0

这对我有用:

private void btnRemove_Click(object sender, EventArgs e) {
    int count = dgvSchedule.SelectedRows.Count;

    while (count != 0) {
        dgvSchedule.Rows.RemoveAt(dgvSchedule.SelectedRows[0].Index);
        count--;
    }
 }
于 2022-01-03T10:29:49.863 回答
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();
    }
}
于 2017-01-06T08:34:58.197 回答
0
   ArrayList bkgrefs = new ArrayList();
                    foreach (GridViewRow rowd in grdOptionExtraDetails.Rows)
                    {
                        CheckBox cbf = (CheckBox)rowd.Cells[1].FindControl("chkbulk");

                            if (cbf.Checked)
                            {
                                rowd.Visible = true;
                                 bkgrefs.Add(Convert.ToString(grdOptionExtraDetails.Data.Rows[rowd.RowIndex]["OptionID"]));

                            }
                            else
                            {
                                grdOptionExtraDetails.Data.Rows.RemoveAt(rowd.DataItemIndex);
                                rowd.Visible = false;
                            }


                    }
于 2020-05-06T12:01:18.260 回答
-1

它对我有用!

private: System::Void MyButton_Delete_Click(System::Object^ sender, System::EventArgs^ e) {
    // Удалить столбец(Row).
    MydataGridView->Rows->RemoveAt(MydataGridView->CurrentCell->RowIndex);
}
于 2021-01-02T15:29:05.043 回答
-2
for (int j = dataGridView1.Rows.Count; j > 0 ; j--)
{
    if (dataGridView1.Rows[j-1].Selected)
        dataGridView1.Rows.RemoveAt(j-1);
}
于 2017-09-03T13:45:43.543 回答
-3

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

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

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

于 2010-01-18T08:41:40.783 回答