1

Access データベース (accdb) と対話する C# Windows フォーム プロジェクトがあります。データベースを問題なく読み取り、それを DataGridView に表示するフォームが 1 つあります。テキストボックス情報をデータベースに送信する別のフォームがあります。

ユーザーがボタン(ボタン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 に答える