[英]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.