[英]How to delete a row from datagridview using c# in Windows application
我在xml中有一個數據庫,我的xml文件是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--This is an XML Generated File-->
<Categories>
<Category>
<CategoryId>1</CategoryId>
<CategoryName>jitu</CategoryName>
</Category>
<Category>
<CategoryId>2</CategoryId>
<CategoryName>ansul</CategoryName>
</Category>
<Category>
<CategoryId>3</CategoryId>
<CategoryName>satish</CategoryName>
</Category>
<Category>
<CategoryId>4</CategoryId>
<CategoryName>tipu</CategoryName>
</Category>
</Categories>
下面是我的C#代碼,用於從DataGridView和xml文件中刪除一行。 但是,如果我從DataGridView中選擇任何行並按Delete鍵,我的代碼將始終刪除第一行。
private void btnDelete_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
string PATH = "xmldata.xml";
ds.Clear();
dtgvCategory.Refresh();
ds.ReadXml(PATH);
row = ds.Tables[0].Rows[0];
int selectedRow = dtgvCategory.SelectedRows.Count;
if (selectedRow > 0)
{
row.Delete();
}
ds.WriteXml(PATH);
ds.AcceptChanges();
}
我想要代碼僅刪除按鈕單擊事件中的選定行
您當前的代碼始終選擇索引0處的row
作為row
,這就是為什么它總是刪除DataGridView中的第一行。
您想要獲取當前選定單元格的行索引,可以嘗試從CurrentCell.RowIndex
屬性獲取它。 此時,您將能夠刪除該索引處的行:
int selectedRow = dtgvCategory.SelectedRows.Count;
if (selectedRow > 0)
{
selectedRowIndex = dtgvCategory.CurrentCell.RowIndex;
row = ds.Tables[0].Rows[selectedRowIndex];
row.Delete();
}
您可以為使用RowStateChanged選擇行時添加事件處理程序:
public int SelectedRow = 0;
private void dtgvCategory_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
// return if not StateChanged
if (e.StateChanged != DataGridViewElementStates.Selected) return;
// then you could put that row in a public variable
SelectedRow = e.Row.Index;
}
現在,在刪除處理程序中,您知道要刪除的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.