简体   繁体   中英

How to make changes to database

How do i change the datatable in database. I am able to delete the rows with my code and see it from datagridview however what do i need to put in to be able to delete it from the database itself.

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Diagnostics;

namespace merge
{
    public partial class Form1 : Form
    {
        private OleDbConnection connection = new OleDbConnection();//setting connection

        public Form1()
        {
            InitializeComponent();
            connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ascrfp04\common\General\Interns\Ng Meng Yee Darren\Workorder tracking\workorder tracking\project.accdb;
Persist Security Info=False;";// connection string from file
        }

        private DataTable GetData4()
        {
            DataTable dt4 = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter("Select * from [tuas barcode]", connection);
            da.Fill(dt4);

            return dt4;
        }
        private void clear_Click(object sender, EventArgs e)
        {
            DataTable dt4 = GetData4();
            foreach (DataRow row in dt4.Rows)
            {
                row.Delete();
            }
            dataGridView1.DataSource = dt4;

        }
    }
}

Given that no-one else has helped you, I'm giving it a go!

Firstly I recommend adding two things to your Form a BindingNavigator and a BindingSource . Both are available under the Data section in the Toolbox. By default the inserted objects are called bindingNavigator1 and bindingSource1 respectively. I will stick to the default names here.

Next highlight the navigator on your form, and in the properties windows under Items set DeleteItem to none. This is important, as we are going to override the standard delete behaviour.

Now in the navigator itself you will see an icon looking like a cross (or x) for delete. Double click this to generate a click method.

You did not show all your code, so I am going to make a few assumptions here. Firstly I assume your GetData4 is called in the constructor. If not add it there.

Now change your GetData4 method to look like this:

private DataTable GetData4()
{
    DataTable dt4 = new DataTable();
    OleDbDataAdapter da = new OleDbDataAdapter("Select * from WorkTimes", connection);
    da.Fill(dt4);
    bindingSource1.DataSource = dt4;
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = bindingSource1;

    return dt4;
}

For my code to work this could equally well be a void method, as I ignore the return value, but you may well want to do some data validation, so I have left the signature "as is".

Now go to the generated method for bindingNavigatorDeleteItem_Click and alter it thus:

private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
{
    DataRowView dRV = (DataRowView)bindingSource1.Current;
    DateTime myDate = (DateTime)dRV["MyDate"];
    string myName = (string)dRV["MyName"];
    if (DeleteRow(myDate, myName))
    {
        GetData4();
    }
}

For illustration purposes, I am using a primary key with two fields MyDate and MyName, respectively DateTime and string. You may well have a single field as the primary key, in which case your task is simpler. It should be obvious, that you simply need to identify the primary key within the clicked row and pass that value to DeleteRow().

Finally DeleteRow() should look something like this:

private bool DeleteRow(DateTime myDate, string myName)
{
    bool ret = false;
    connection.Open();
    using (var cmd = new OleDbCommand("DELETE * FROM YourTable WHERE MyDate = ? AND MyName = ?", connection))
    {
        cmd.Parameters.Add(new OleDbParameter
        {
            ParameterName = "@MyDate",
            DbType = DbType.DateTime,
            Value = myDate
        });
        cmd.Parameters.Add(new OleDbParameter
        {
            ParameterName = "@MyName",
            DbType = DbType.String,
            Value = myName
        });
        ret = (cmd.ExecuteNonQuery() == 1);
    }
    connection.Close();
    return ret;
}

By way of explanation: 1) Note the I am using parameters to pass the primary key to the Command; this is the recommended way to do this. In passing note that the naming of parameters when using OleDb is irrelevant: I am using ? as a placeholder - I could have used @myDate and @MyName instead. All that is important id to get the order of the parameters correct. 2) ExecuteNonQuery() returns the number of rows affected. This should be one as only the current row is deleted.

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