C# 如何删除选定的 DataGridViewRow 并更新连接的数据库表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2084346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete a selected DataGridViewRow and update a connected database table?
提问by Woody
I have a DataGridView
control on a Windows Forms application (written with C#).
我有一个DataGridView
Windows 窗体应用程序的控件(用 C# 编写)。
What I need is: when a user selects a DataGridViewRow, and then clicks on a 'Delete' button, the row should be deleted andnext, the database needs to be updated using table adapters.
我需要的是:当在“删除”按钮,用户选择的DataGridViewRow,然后点击,该行应删除和未来,数据库需要使用表适配器更新。
This is what I have so far:
这是我到目前为止:
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
}
}
Furthermore, this only deletes one row. I would like it where the user can select multiple rows.
此外,这只会删除一行。我希望用户可以选择多行。
回答by Navid Farhadi
This code removes selected items of dataGridView1
:
此代码删除所选项目dataGridView1
:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
}
回答by TheVillageIdiot
here is one very simple example:
这是一个非常简单的例子:
ASPX:
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"/>
Code Behind:
背后的代码:
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;
}
}
you will have to use checkboxes or some other mechanism to allow users to select multiple rows and then you can browse the rows for ones with the checkbox checked and then remove those rows.
您将不得不使用复选框或其他一些机制来允许用户选择多行,然后您可以浏览选中复选框的行,然后删除这些行。
回答by serge_gubenko
I have written the following code, please take a look:
我写了以下代码,请看:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
if (!row.IsNewRow) dataGridView1.Rows.Remove(row);
using the Index
of the selected row still could work; see if the code below will do the trick:
使用Index
所选行的 仍然可以工作;看看下面的代码是否可以解决问题:
int selectedCount = dataGridView1.SelectedRows.Count;
while (selectedCount > 0)
{
if (!dataGridView1.SelectedRows[0].IsNewRow)
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
selectedCount--;
}
I hope this helps, regards.
我希望这会有所帮助,问候。
回答by huncyrus
private void btnDelete_Click(object sender, EventArgs e)
{
if (e.ColumIndex == 10)// 10th column the button
{
dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
This solution can be delete a row (not selected, clicked row!) via "e" param.
此解决方案可以通过“e”参数删除一行(未选中,单击行!)。
回答by Filip
private void buttonRemove_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
Removes rows which indexes are in selected cells. So, select any cells, and their corresponding rows will be removed.
删除索引位于选定单元格中的行。因此,选择任何单元格,它们对应的行将被删除。
回答by littlecodefarmer758
To delete multiple rows in datagrid, c#
要删除数据网格中的多行,c#
parts of my code:
我的代码的一部分:
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();
}
回答by Sarvar Nishonboev
have a look this way:
看看这个:
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);
}
回答by Sherif Hamdy
Try this:
尝试这个:
if (dgv.SelectedRows.Count>0)
{
dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
回答by Sarah Chaygani
Well, this is how I usually delete checked rows by the user from a DataGridView
, if you are associating it with a DataTable from a Dataset
(ex: DataGridView1.DataSource = Dataset1.Tables["x"]
), then once you will make any updates (delete, insert,update) in the Dataset
, it will automatically happen in your DataGridView
.
好吧,这就是我通常从 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);
}
}
回答by Sarah Chaygani
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());
}
}