【问题标题】:How to delete a row from datagridview using c# in Windows application如何在 Windows 应用程序中使用 c# 从 datagridview 中删除一行
【发布时间】:2015-07-02 20:38:01
【问题描述】:

我在 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 中选择任何行并按下删除按钮,我的代码总是会删除第一行。

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

我想要在按钮单击事件 上仅删除一个选定行的代码

【问题讨论】:

    标签: c# xml datagridview


    【解决方案1】:

    您当前的代码始终将索引 0 处的行选择为 row,这就是它始终删除 DataGridView 中第一行的原因。

    您想改为get row index of currently selected cell,您可以尝试从CurrentCell.RowIndex 属性中获取它。此时您将能够删除该索引处的行:

    int selectedRow = dtgvCategory.SelectedRows.Count;
    if (selectedRow > 0)
    {
        selectedRowIndex = dtgvCategory.CurrentCell.RowIndex;
        row = ds.Tables[0].Rows[selectedRowIndex];
        row.Delete();
    }
    

    【讨论】:

    • 感谢先生您的代码完美运行.....现在我希望代码使用 c# 代码更新 xml 文件中的记录。请提供一些解决方案或想法
    【解决方案2】:

    您可以在使用 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;
        }
    

    现在在您的删除处理程序中,您知道要删除哪一行。

    https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrowstatechangedeventargs%28v=vs.110%29.aspx

    【讨论】:

    • 感谢您的回答,但它无法正常工作..它给出错误。错误 1 ​​无法将类型 'System.Windows.Forms.DataGridViewRow' 隐式转换为 'int' D:\IMS\IMS\Form1.cs 163 27 IMS
    • 感谢您的回复,但是当我们再次单击删除按钮时,它会删除第一行,我们选择第二行或任何其他行。我们只想删除选定的行
    • e.Row.Index 返回什么?什么是 e.Row.State?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    相关资源
    最近更新 更多