简体   繁体   English

使用C#用CSV文件填充DataGridView,并使用结果更新Access数据库

[英]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). 我有一个与Access数据库(accdb)交互的C#Windows窗体项目。 I have one form that reads the database just fine, and displays it into a DataGridView. 我有一个表单可以很好地读取数据库,并将其显示在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) . 我有另一种形式(见下图),允许用户单击按钮(按钮1)打开CSV文件,使用“openFileDialog”,并在窗体上的dataGridView中显示所选文件的内容(如下所示)

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. 我的目标:我希望在同一表单上有一个按钮(按钮3),将dataGridView的显示结果提交到前面提到的Access数据库中。

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. 当CSV文件在Access数据库外部时,使用数据集对象来处理数据是一项挑战。 To resolve this you can programmatically persist updates from the DataGridView to the Access database. 要解决此问题,您可以以编程方式将更新从DataGridView持久保存到Access数据库。

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) 假设您要做的就是获取CSV的内容并将它们插入到表中,您可以循环访问数据集并调用insert命令(当然还有参数化查询)

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 您需要将DataSet移动为类级变量

public partial class Import : Form
{
     DataSet dataset;

and then later in button1_Click assign it instead of declaring and assigning it 然后在button1_Click中分配它而不是声明和分配它

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

You need to look at creating an UPDATE command for your Data Adapter. 您需要查看为数据适配器创建UPDATE命令。

This Guide below will get you started in understanding Data Adapters better :- 以下本指南将帮助您更好地了解数据适配器: -

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

Good Luck!! 祝好运!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#中使用datagridview更新Access数据库 - How to update Access database using a datagridview in C# 如何使用C#将datagridview更新到数据库? - how to update datagridview to database using c#? 使用 C# 使用 DataGridView 中的值更新数据库 - Update database with values in DataGridView using C# C#-尝试使用datagridview(也使用OleDbCommandBuilder)更新访问数据库时出现“更新语句中的语法错误” - C# - “Syntax error in update statement” when trying to update the access database using datagridview (also using OleDbCommandBuilder) 使用C#在Access中更新链接的CSV文件 - Update linked CSV File in Access using C# 使用C#以编程方式将CSV文件导入Access数据库 - Programmatically import a CSV file into an Access database using C# 像Access一样,如何使用ac#datagridview更新数据库文件? - How to use a c# datagridview to update a database file just like Access does? 如何在C#中使用datagridview列名更新Access数据库的特定列 - How to update specific columns of access database using datagridview column name in C# c# - 如何为datagridview实现更新按钮并使用dataHandler类(数据访问类)将值保存到数据库 - how to implement update button for datagridview and save values to database using a dataHandler class(data access class) c# 使用C#中的datagridview和navigator绑定删除和更新ms Access数据库 - Delete and Update ms access database using a datagridview and navigator binding in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM