简体   繁体   中英

How to Delete Row By ID From Datatable and Database

Here is full code at the moment what I have done. So basically I'm creating a DataTable , then I'm connecting my DataTable with a database. I can edit person by ID, but I don't know how to delete person by ID. I want a full row to be deleted.

As well, in the part where I edit the DataTable , if I choose not to edit table, I get some null reference error

Object reference not set to an instance of an object.

My code:

        /*
        * Creating DataTable
        */

        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("ID", typeof(int)));
        dt.Columns.Add(new DataColumn("Vards", typeof(string)));
        dt.Columns.Add(new DataColumn("Uzvards", typeof(string)));

        /*
        * Connecting to DataBase
        */

        string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
        OleDbConnection con = new OleDbConnection(ConnectionString);
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM PERSONA", con);
        con.Open();
        OleDbDataReader dataReader = cmd.ExecuteReader();

        while (dataReader.Read())
        {
             DataRow dr = dt.NewRow();
             dr["ID"] = dataReader["ID"];
             dr["Vards"] = dataReader["Vards"];
             dr["Uzvards"] = dataReader["Uzvards"];
             dt.Rows.Add(dr);
        }

        con.Close();
        dt.AcceptChanges();
        PrintDataTable(dt);

        Console.WriteLine();


         /* Edit Person in DataTable */

        Console.WriteLine("Kuru ID vēlaties labot?");
        int labosana = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Vai tiešām vēlaties labot šo ierakstu?");
        string vaiLabot = Console.ReadLine();

        if (vaiLabot == "yes")
        {
            Console.WriteLine("Ievadiet jauno vārdu:");
            string vards = Console.ReadLine();

            Console.WriteLine("Ievadiet jauno uzvārdu:");
            string uzvards = Console.ReadLine();

            dt.Rows[labosana-1]["Vards"] = vards;
            dt.Rows[labosana-1]["Uzvards"] = uzvards;
        }
        else
        {
            Console.WriteLine("Jūs atteicāties labot!");
        }

        /*
        * Adding Edited Person to Database
        */

        OleDbCommand upCmd = new OleDbCommand("UPDATE PERSONA SET Vards=?,Uzvards=? WHERE ID=?", con);
        upCmd.Parameters.Add(new OleDbParameter("@Vards",OleDbType.VarChar));
        upCmd.Parameters.Add(new OleDbParameter("@Uzvards", OleDbType.VarChar));
        upCmd.Parameters.Add(new OleDbParameter("@ID", OleDbType.Integer));

        foreach(DataRow dro in dt.GetChanges().Rows)
        {

         if (dro.RowState == DataRowState.Modified)
         {
             upCmd.Parameters[0].Value = dro[1];
             upCmd.Parameters[1].Value = dro[2];
             upCmd.Parameters[2].Value = dro[0];
             con.Open();
             upCmd.ExecuteNonQuery();
             con.Close();
         }

        }

I tried a ton of code. But none of them seems to work. Tried something like this to delete by the Name.

for(int i = dt.Rows.Count-1; i >= 0; i--)
{
    DataRow dr = dt.Rows[i];
    if (dr["Vards"] == "Name")
        dr.Delete();
}

Use this code for deleting by Id from database:

public int DeleteById(int Id)
{
        string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";

        OleDbConnection con = new OleDbConnection(ConnectionString);
        OleDbCommand cmd = new OleDbCommand("DELETE FROM PERSONA WHERE ID = @ID", con);
        cmd.Parameters.Add(new OleDbParameter("ID", Id));

        return cmd.ExecuteNonQuery();
}

Updated: try this -- To delete from the DataTable

    DataRow rowToBeDeleted;
for(int i = dt.Rows.Count-1; i >= 0; i--)
    {
        DataRow dr = dt.Rows[i];
        if (dr["Vards"] == "Name")
rowToBeDeleted = dr;            

    }

dt.Rows.Remove(rowToBeDeleted );

Or if using LINQ, you can also do something like

var dr = dt.AsEnumerable().Where(row => row.Field<string>("Vards") == "Name").SingleOrDefault();
            dt.Rows.Remove(dr);

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