简体   繁体   中英

How to delete a row from datagridview using c# in Windows application

I have a database in xml my xml file is:

      <?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>

My c# code is following for deleting a row from DataGridView and xml file. But my code always delete first row if I select any row from DataGridView and press the delete button.

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

I want code that delete only one selected row on button click event 在此处输入图片说明

Your current code always select row at index 0 as row , that's why it always delete the first row in the DataGridView.

You want to get row index of currently selected cell instead and you can try to get it from CurrentCell.RowIndex property. At this point you'll be able to delete row at that index :

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

you could add an eventhandler for when the row is selected using 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;
    }

Now in your delete handler you know which row to delete.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM