简体   繁体   中英

Using C# to populate a DataGridView with CSV file, and update Access database with results

I have a C# Windows Forms project that interacts with an Access database (accdb). I have one form that reads the database just fine, and displays it into a DataGridView. I have another form that submits textbox information into the database just as fine.

I have another form (see image below) that allows the user to click a button (button 1) to open a CSV file, using "openFileDialog", and display the selected file's contents in the dataGridView on the form (example shown below) .

MY GOAL: I want a button (button 3), on that same form, to submit the dataGridView's displayed results into the previously mentioned Access database.

It seems like I have all of the components I need. It feels like I'm not too far off, but there still seems to be something wrong and/or missing in my code. I've been trying to accomplish this for weeks. PLEASE HELP!!!

Here is both, a screen shot of the form, and the full code for the form. ALL help is GREATLY appreciated!

在此输入图像描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Configuration;
using System.Data.OleDb;

namespace csvToGrid
{
    public partial class Import : Form
        {
            public Import()
                {
                    InitializeComponent();
                }
        public void button1_Click(object sender, EventArgs e)
            {
                string delimiter = ",";
                string tablename = "medTable";
                DataSet dataset = new DataSet();
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                filename = openFileDialog1.FileName;
                                StreamReader sr = new StreamReader(filename);
                                string csv = File.ReadAllText(openFileDialog1.FileName);
                                dataset.Tables.Add(tablename);
                                dataset.Tables[tablename].Columns.Add("Prescription");
                                dataset.Tables[tablename].Columns.Add("Customer Name");
                                dataset.Tables[tablename].Columns.Add("Medication");
                                dataset.Tables[tablename].Columns.Add("Quantity");
                                dataset.Tables[tablename].Columns.Add("Date Filled");

                                string allData = sr.ReadToEnd();
                                string[] rows = allData.Split("\r".ToCharArray());

                                foreach (string r in rows)
                                    {
                                        string[] items = r.Split(delimiter.ToCharArray());
                                        dataset.Tables[tablename].Rows.Add(items);
                                    }
                                this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
                                MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
                            }
                        else
                            {
                                this.Close();
                            }
                }
            }

        public string filename { get; set; }


        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
            {

            }

        private void Import_Load(object sender, EventArgs e)
            {

            }

        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)

            //remove the semicolon, and add brackets below after line
            {   
                //create the connection string
                string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Search\\Database.accdb";
                //create the database query
                string query = "SELECT * FROM script_Orders";
                //create an OleDbDataAdapter to execute the query
                OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
                //create a command builder
                OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
                //create a DataTable to hold the query results
                DataTable dTable = new DataTable();
                //fill the DataTable
                dAdapter.Fill(dTable);
                //the DataGridView
                DataGridView dataGridView1 = new DataGridView();
                //BindingSource to sync DataTable and DataGridView
                BindingSource bSource = new BindingSource();
                //set the BindingSource DataSource
                bSource.DataSource = dTable;
                //set the DataGridView DataSource
                dataGridView1.DataSource = bSource;
                // An update function to get the changes back into the database.
                dAdapter.Update(dTable);
            }

        }
    }

在此输入图像描述

Examples are more than welcome!

The challenge comes from using a dataset object to work with the data while the CSV file is external to the Access database. To resolve this you can programmatically persist updates from the DataGridView to the Access database.

Insert Example

DataRow anyRow = DatasetName.ExistingTable.NewRow();
anyRow.FirstName = "Jay";
anyRow.LastName = "Stevens";
ExistingTable.Rows.Add(anyRow);

Update Example

dsCustomers1.Customers[4].CompanyName = "Wingtip Toys";
dsCustomers1.Customers[4].City = "Buffalo";

Delete Example

dsCustomers1.Customers.Rows[0].Delete();

Hope this helps. Cheers.

Assuming all you want to do is take the contents of the CSV and insert them into your table you can just loop though your dataset and call an insert command (with a parameterized query of course)

var AccessCnn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", @"C:\YOURDBNAME.accdb");

using (OleDbConnection accessCnn = new OleDbConnection(AccessCnn))
{


    //Create The Command
    var accessCmd = new OleDbCommand(@"INSERT INTO script_Orders  
                                       (Prescription, [Customer Name], Medication, Quantity, [Date Filled])
                                    VALUES (?,?,?,?,?)", accessCnn);

   foreach(var row in dataset.Tables["medTable"].Rows)
   {
      accessCmd.Parameters.Clear();

      accessCmd.Parameters.AddWithValue("?", row["Prescription"]);
      accessCmd.Parameters.AddWithValue("?", row["Customer Name"]);
      accessCmd.Parameters.AddWithValue("?", row["Medication"]);
      accessCmd.Parameters.AddWithValue("?", row["Quantity"]);
      accessCmd.Parameters.AddWithValue("?", row["Date Filled"]);

      ccessCmd.ExecuteNonQuery();
   }


}

You will need to move your DataSet to be a class level variable

public partial class Import : Form
{
     DataSet dataset;

and then later in button1_Click assign it instead of declaring and assigning it

string tablename = "medTable";
dataset = new DataSet();                        

You need to look at creating an UPDATE command for your Data Adapter.

This Guide below will get you started in understanding Data Adapters better :-

http://msdn.microsoft.com/en-us/library/33y2221y.aspx

Good Luck!!

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