1

我有一个与 Access 数据库 (accdb) 交互的 C# Windows 窗体项目。我有一个表格可以很好地读取数据库,并将其显示到 DataGridView 中。我有另一个表单,可以将文本框信息提交到数据库中。

我有另一个表单(见下图),它允许用户单击按钮(按钮 1)以使用“openFileDialog”打开 CSV 文件,并在表单上的 dataGridView 中显示所选文件的内容(示例如下所示)

我的目标:我想要一个按钮(按钮 3),在同一个表单上,将 dataGridView 的显示结果提交到前面提到的 Access 数据库中。

似乎我拥有我需要的所有组件。感觉好像我离得太远了,但我的代码中似乎仍然存在错误和/或缺失。几周以来,我一直在努力实现这一目标。请帮忙!!!

这是表单的屏幕截图和表单的完整代码。非常感谢所有帮助!

在此处输入图像描述

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

        }
    }

在此处输入图像描述

例子非常受欢迎!

4

3 回答 3

2

挑战来自使用数据集对象来处理数据,而 CSV 文件位于 Access 数据库外部。要解决此问题,您可以以编程方式将更新从 DataGridView 持久保存到 Access 数据库。

插入示例

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

更新示例

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

删除示例

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

希望这可以帮助。干杯。

于 2012-11-26T19:56:36.553 回答
1

假设您要做的就是获取 CSV 的内容并将它们插入到您的表中,您可以遍历数据集并调用插入命令(当然使用参数化查询)

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


}

您需要将 DataSet 移动为类级别变量

public partial class Import : Form
{
     DataSet dataset;

然后稍后在 button1_Click 中分配它而不是声明和分配它

string tablename = "medTable";
dataset = new DataSet();                        
于 2012-11-26T20:42:02.137 回答
0

您需要查看为您的数据适配器创建一个 UPDATE 命令。

下面的本指南将帮助您更好地了解数据适配器:-

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

祝你好运!!

于 2012-11-26T20:39:39.233 回答