Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#用CSV文件填充DataGridView,并用结果更新Access数据库_C#_Database_Ms Access_Datagridview - Fatal编程技术网

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

使用C#用CSV文件填充DataGridView,并用结果更新Access数据库,c#,database,ms-access,datagridview,C#,Database,Ms Access,Datagridview,我有一个与Access数据库(accdb)交互的C#Windows窗体项目。我有一个表单可以很好地读取数据库,并将其显示到DataGridView中。我有另一个表单,它将文本框信息提交到数据库中 我有另一个表单(见下图),允许用户单击按钮(按钮1),使用“openFileDialog”打开CSV文件,并在表单上的dataGridView中显示所选文件的内容(示例如下所示) 我的目标:我想要一个相同表单上的按钮(按钮3),将dataGridView的显示结果提交到前面提到的Access数据库中。

我有一个与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);
            }

        }
    }


非常欢迎使用示例

当CSV文件位于Access数据库外部时,挑战来自使用dataset对象处理数据。要解决此问题,可以通过编程将更新从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();
删除示例

dsCustomers1.Customers[4].CompanyName = "Wingtip Toys";
dsCustomers1.Customers[4].City = "Buffalo";
dsCustomers1.Customers.Rows[0].Delete();

希望这有帮助。干杯。

您需要考虑为数据适配器创建更新命令

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


祝你好运

假设您只需要获取CSV的内容并将其插入到表中,您只需在数据集中循环并调用insert命令(当然是参数化查询)

您需要将数据集移动为类级变量

public partial class Import : Form
{
     DataSet dataset;
然后稍后在button1\u中单击assign,而不是声明和分配它

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

这是一个很好的例子,说明了您想要什么,但是您没有解释您遇到的实际问题/错误是什么。您是否遇到了任何错误?如果是这样,请说明错误是什么大的否定,我的朋友。单击上面显示的表单中的“按钮1”并成功地将CSV文件导入dataGridView后,没有警告、错误或消息。@DJKRAZE导入成功,其中有“\r”。注意下面的行:
string delimiter=“,”我遇到的问题是以下代码:
public void button1\u Click(object sender,EventArgs e)
假设从CSV导入的所有行都将插入到访问表中是否安全?还是您也在更新行?@ConradFrix我打算导入所有行。只是还在想办法。:-)你键入的内容非常有意义。那么,我想我的下一个问题是:“我需要在我的代码中进行插入和更新,这样数据就会进入数据库并进行更新吗?”如果不需要,我应该使用哪一个,我应该在代码中的什么位置插入它?谢谢你的回复!只要在将数据写入数据库之前更改了数据,就只需要插入。否则,您也需要更新。您可以将代码放入button3\u Click事件中。由于我将首先从CSV导入数据,因此我可以安全地假设数据在写入数据库之前会发生更改吗?是的,您可以这样假设。@Geo,如果我的答案帮助您解决了问题,请将其标记为所选答案。干杯。以上答案是关于如何插入和更新的评论