簡體   English   中英

使用C#用CSV文件填充DataGridView,並使用結果更新Access數據庫

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

我有一個與Access數據庫(accdb)交互的C#Windows窗體項目。 我有一個表單可以很好地讀取數據庫,並將其顯示在DataGridView中。 我有另一種表單,可以將文本框信息提交到數據庫中。

我有另一種形式(見下圖),允許用戶單擊按鈕(按鈕1)打開CSV文件,使用“openFileDialog”,並在窗體上的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);
            }

        }
    }

在此輸入圖像描述

例子非常受歡迎!

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

希望這可以幫助。 干杯。

假設您要做的就是獲取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();
   }


}

您需要將DataSet移動為類級變量

public partial class Import : Form
{
     DataSet dataset;

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

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

您需要查看為數據適配器創建UPDATE命令。

以下本指南將幫助您更好地了解數據適配器: -

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

祝好運!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM