C# 如何将打开的.csv文件绑定到DataGridView中以前创建的表以允许其编辑?

C# 如何将打开的.csv文件绑定到DataGridView中以前创建的表以允许其编辑?,c#,winforms,csv,datatable,C#,Winforms,Csv,Datatable,我有以下代码。这是一个预算助理计划。用户通过文本字段和“添加行”按钮编辑表格,将其保存为.csv,然后下次打开以继续编辑。现在,程序可以完美地保存和打开.csv文件,但问题是。。它不允许在加载.csv后进行编辑。就我所见,问题在于加载.csv文件时它会创建一个新表(数据集),但我不是很确定。如果你能就如何进行给我一些建议,我将不胜感激 using System; using System.Collections.Generic; using System.ComponentModel; usin

我有以下代码。这是一个预算助理计划。用户通过文本字段和“添加行”按钮编辑表格,将其保存为.csv,然后下次打开以继续编辑。现在,程序可以完美地保存和打开.csv文件,但问题是。。它不允许在加载.csv后进行编辑。就我所见,问题在于加载.csv文件时它会创建一个新表(数据集),但我不是很确定。如果你能就如何进行给我一些建议,我将不胜感激

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using CsvHelper;
using ExcelDataReader;
using Microsoft.Office.Interop.Excel;
using DataTable = System.Data.DataTable;
using Excel = Microsoft.Office.Interop.Excel;



namespace WindowsFormsApp2
{
    public partial class Form1 : Form 
    {

        DataSet ds = new DataSet();
        DataTable budgetTable = new DataTable();


        public Form1()
        {
            InitializeComponent();

            DataTable budgetTable = ds.Tables.Add("MainTable");
            budgetTable.Columns.Add("id", typeof(Int32));
            budgetTable.Columns.Add("date", typeof(DateTime));
            budgetTable.Columns.Add("type", typeof(String));
            budgetTable.Columns.Add("name", typeof(String));
            budgetTable.Columns.Add("expenses", typeof(Int32));
            budgetTable.Columns.Add("income", typeof(Int32));
            budgetTable.Columns.Add("saldo", typeof(Int32));

            var date = DateTime.ParseExact("29MAR18", "ddMMMyy", CultureInfo.InvariantCulture);

            DataRow row = budgetTable.NewRow();
            row["id"] = "01";
            row["date"] = date;
            row["type"] = cbbxType.Text;
            row["name"] = nameField.Text;
            row["expenses"] = expenseField.Text;
            row["income"] = incomeField.Text;
            row["saldo"] = 0;
            budgetTable.Rows.Add(row);
            DtgTable.DataSource = budgetTable;
            budgetTable.Rows.Clear();
        }


        //adds a row to the table
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(cbbxType.Text) ||
                string.IsNullOrWhiteSpace(expenseField.Text))
            {
                MessageBox.Show("'Type','Expence','Income' fields cannot be empty!");
            }
            else
              budgetTable.Rows.Add(null, dateTime.Text, cbbxType.Text, nameField.Text, expenseField.Text, incomeField.Text);
        }

        //deletes everything from the table
        private void btnDeleteItem_Click(object sender, EventArgs e)
        {
            budgetTable.Rows.Clear();
        }

        //deletes selected row from the table
        private void button1_Click_1(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in DtgTable.SelectedRows)
            {
                budgetTable.Rows.RemoveAt(row.Index);
            }
        }

        //enumerates ID values
        private void dtgTable_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {

        }

        //calculates saldo cell on a specified row (you have to click the saldo cell)
        private void dtgTable_CellValidated(object sender, DataGridViewCellEventArgs e)
        {

        }

        //calculates overall balance
        private void btnCalcBalance_Click(object sender, EventArgs e)
        {

        }

        //_______________________MenuStrip__________________________________________//
        //Opening file      WORKS                                                   //
        //__________________________________________________________________________//
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string FileName;
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Open CSV File";
            dialog.Filter = "CSV Files (*.csv)|*.csv";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                FileName = dialog.FileName;
            }
            else
            {
                return;
            }

                OleDbConnection conn = new OleDbConnection
                       ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
                         Path.GetDirectoryName(FileName) +
                         "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");

                conn.Open();

                OleDbDataAdapter adapter = new OleDbDataAdapter
                       ("SELECT * FROM " + Path.GetFileName(FileName), conn);

                DataSet ds = new DataSet("Temp");
                adapter.Fill(ds);

                conn.Close();

                DtgTable.DataSource = ds;
                DtgTable.DataMember = "Table";

        }


        //__________________________________________________________________________________
        //Saving file to .csv   WORKS
        //___________________________________________________________________________________
        public void writeCSV(DataGridView gridIn, string outputFile)
        {
            //test to see if the DataGridView has any rows
            if (gridIn.RowCount > 0)
            {
                string value = "";
                DataGridViewRow dr = new DataGridViewRow();
                StreamWriter swOut = new StreamWriter(outputFile);

                //write header rows to csv
                for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
                {
                    if (i > 0)
                    {
                        swOut.Write(",");
                    }
                    swOut.Write(gridIn.Columns[i].HeaderText);
                }

                swOut.WriteLine();

                //write DataGridView rows to csv
                for (int j = 0; j <= gridIn.Rows.Count - 1; j++)
                {
                    if (j > 0)
                    {
                        swOut.WriteLine();
                    }

                    dr = gridIn.Rows[j];

                    for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
                    {
                        if (i > 0)
                        {
                            swOut.Write(",");
                        }

                        value = dr.Cells[i].Value.ToString();
                        //replace comma's with spaces
                        value = value.Replace(',', ' ');
                        //replace embedded newlines with spaces
                        value = value.Replace(Environment.NewLine, " ");

                        swOut.Write(value);
                    }
                }
                swOut.Close();
            }
        }
        private void saveToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            writeCSV(DtgTable, "result.csv");
            MessageBox.Show("Converted successfully to *.csv format");
        }

        //___________________________________________________________________________________
        //about
        //___________________________________________________________________________________
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
            {
                MessageBox.Show("");
            }


    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用System.Data.OleDb;
使用System.Data.SqlClient;
使用系统图;
利用制度全球化;
使用System.IO;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Xml;
使用System.Xml.Linq;
使用CsvHelper;
使用ExcelDataReader;
使用Microsoft.Office.Interop.Excel;
使用DataTable=System.Data.DataTable;
使用Excel=Microsoft.Office.Interop.Excel;
命名空间WindowsFormsApp2
{
公共部分类Form1:Form
{
数据集ds=新数据集();
DataTable budgetTable=新DataTable();
公共表格1()
{
初始化组件();
DataTable budgetTable=ds.Tables.Add(“MainTable”);
添加(“id”,typeof(Int32));
添加(“日期”,类型(日期时间));
budgetTable.Columns.Add(“type”,typeof(String));
budgetTable.Columns.Add(“name”,typeof(String));
可预算。列。添加(“费用”,类型(Int32));
可预算。列。添加(“收入”,类型(Int32));
添加(“saldo”,typeof(Int32));
var date=DateTime.ParseExact(“2018年3月29日”,“ddMMMyy”,CultureInfo.InvariantCulture);
DataRow行=budgetTable.NewRow();
行[“id”]=“01”;
行[“日期”]=日期;
行[“类型”]=cbbxType.Text;
行[“名称”]=nameField.Text;
行[“费用”]=expenseField.Text;
行[“收入”]=incomeField.Text;
行[“saldo”]=0;
可预算.行.添加(行);
DtgTable.DataSource=budgetTable;
budgetTable.Rows.Clear();
}
//向表中添加一行
私有无效按钮1\u单击(对象发送者,事件参数e)
{
if(string.IsNullOrWhiteSpace(cbbxType.Text)||
string.IsNullOrWhiteSpace(expenseField.Text))
{
MessageBox.Show(“'Type'、'Expence'、'Income'字段不能为空!”);
}
其他的
budgetTable.Rows.Add(null,dateTime.Text,cbbxType.Text,nameField.Text,expenseField.Text,incomeField.Text);
}
//删除表中的所有内容
私有无效btnDeleteItem_单击(对象发送者,事件参数e)
{
budgetTable.Rows.Clear();
}
//从表中删除选定行
私有无效按钮1\u单击\u 1(对象发送者,事件参数e)
{
foreach(DtgTable.SelectedRows中的DataGridViewRow行)
{
budgetTable.Rows.RemoveAt(row.Index);
}
}
//枚举ID值
私有void dtgTable_RowPostPaint(对象发送方,DataGridViewRowPostPaintEventArgs e)
{
}
//计算指定行上的saldo单元格(必须单击saldo单元格)
私有void dtgTable_CellValidated(对象发送方,DataGridViewCellEventArgs e)
{
}
//计算总余额
私有void btnCalcBalance_单击(对象发送方,事件参数e)
{
}
//_______________________梅努斯蒂普__________________________________________//
//打开文件工作//
//__________________________________________________________________________//
私有void openToolStripMenuItem\u单击(对象发送方,事件参数e)
{
字符串文件名;
OpenFileDialog=新建OpenFileDialog();
dialog.Title=“打开CSV文件”;
dialog.Filter=“CSV文件(*.CSV)|*.CSV”;
if(dialog.ShowDialog()==DialogResult.OK)
{
FileName=dialog.FileName;
}
其他的
{
返回;
}
OLEDB连接连接=新OLEDB连接
(“Provider=Microsoft.Jet.OleDb.4.0;数据源=”+
Path.GetDirectoryName(文件名)+
“扩展属性=\”文本;HDR=YES;FMT=Delimited\”;
conn.Open();
OleDbDataAdapter=新OleDbDataAdapter
(“从“+Path.GetFileName(FileName),conn中选择*);
数据集ds=新数据集(“临时”);
适配器。填充(ds);
康涅狄格州关闭();
DtgTable.DataSource=ds;
DtgTable.DataMember=“表”;
}
//__________________________________________________________________________________
//将文件保存到.csv有效
//___________________________________________________________________________________
public void writeCSV(DataGridView gridIn,string outputFile)
{
//测试DataGridView是否有任何行
如果(gridIn.RowCount>0)
{
字符串值=”;
DataGridViewRow dr=新建DataGridViewRow();
StreamWriter swOut=新的StreamWriter(输出文件);
//将标题行写入csv
对于(int i=0;i 0)
{
写出(“,”);
}
写(gri)
private void SetTableColumns() {
  BudgetTable = new DataTable();
  BudgetTable.Columns.Add("Id", typeof(Int32));
  BudgetTable.Columns.Add("Date", typeof(DateTime));
  BudgetTable.Columns.Add("Type", typeof(String));
  BudgetTable.Columns.Add("Name", typeof(String));
  BudgetTable.Columns.Add("Expenses", typeof(decimal));
  BudgetTable.Columns.Add("Income", typeof(decimal));
  BudgetTable.Columns.Add("Balance", typeof(decimal));
  BudgetTable.Columns["Balance"].Expression = "Income - Expenses";
}
private void FillDataTableFromCSV(string file) {
  StreamReader sr = new StreamReader(file);
  string[] splitArray;
  int maxColumns = BudgetTable.Columns.Count - 1; // <- the last column is a computed column we dont want to save
  int curColCount = maxColumns;
  string curLine = sr.ReadLine();
  if (curLine != null) {
    DataRow newRow;
    while ((curLine = sr.ReadLine()) != null) {
      splitArray = curLine.Split('\t');
      curColCount = maxColumns;
      if (splitArray.Length < maxColumns) {
        curColCount = splitArray.Length;
      }
      newRow = BudgetTable.Rows.Add();
      for (int i = 0; i < curColCount; i++) {
        newRow[i] = splitArray[i];
      }
    }
  }
  sr.Close();
}
public class BudgetItem {
  public int Id { get; set; }
  private DateTime _Date { get; set; }
  public string Date => _Date.ToShortDateString();
  public string Type { get; set; }
  public string Name { get; set; }
  public decimal Expense { get; set; }
  public decimal Income { get; set; }
  public decimal Balance => Income - Expense;

  public BudgetItem(int id, DateTime date, string type, string name, decimal expense, decimal income) {
    Id = id;
    _Date = date;
    Type = type;
    Name = name;
    Expense = expense;
    Income = income;
  }
}
private void FillListFromCSV(string file) {
  BudgetList = new BindingList<BudgetItem>();
  StreamReader sr = new StreamReader(file);
  string curLine = sr.ReadLine(); // <- ignore header row
  if (curLine != null) {
    BudgetItem BI;
    while ((curLine = sr.ReadLine()) != null) {
      if ((BI = GetBudgetItemFromString(curLine)) != null) {
        BudgetList.Add(BI);
      }
      else {
        MessageBox.Show("Error invalid Budget Item: " + curLine);
      }
    }
  }
  sr.Close();
}
private BudgetItem GetBudgetItemFromString(string data) {
  string[] arr = data.Split('\t');
  if (arr.Length >= 6) {
    int.TryParse(arr[0], out int id);
    DateTime.TryParse(arr[1], out DateTime date);
    decimal.TryParse(arr[4], out decimal exp);
    decimal.TryParse(arr[5], out decimal inc);
    return new BudgetItem(id, date, arr[2], arr[3], exp, inc);
  }
  return null;
}
private void WriteGridToCSV(DataGridView dgv, string filename) {
  StreamWriter sw = new StreamWriter(filename);
  // write headers - we do not want to write the balance column
  for (int col = 0; col < dgv.Columns.Count - 1; col++) {
    sw.Write(dgv.Columns[col].HeaderText);
    if (col < dgv.Columns.Count - 2) {
      sw.Write("\t");
    }
  }
  sw.WriteLine();
  // Write data - we do not want to save the balance column
  for (int row = 0; row < dgv.RowCount; row++) {
    for (int col = 0; col < dgv.ColumnCount - 1; col++) {
      if (!dgv.Rows[row].IsNewRow) {
        sw.Write(dgv.Rows[row].Cells[col].Value);
        if (col < dgv.ColumnCount - 2) {
          sw.Write("\t");
        }
      }
    }
    sw.WriteLine();
  }
  sw.Close();
  MessageBox.Show("Write finished");
}
// for the DataTable
DtgTable.DataSource = BudgetTable;

// For the `BindingList<BudgetItem>
DtgTable.DataSource = BudgetList;
private void btnDelete_Click(object sender, EventArgs e) {
  foreach (DataGridViewRow row in DtgTable.SelectedRows) {
    DataRowView dr = (DataRowView)row.DataBoundItem;
    dr.Delete();
  }
  DtgTable.DataSource = null;
  DtgTable.DataSource = BudgetTable;
  }
}
private void btnDelete_Click(object sender, EventArgs e) {
  BudgetItem target;
  foreach (DataGridViewRow row in DtgTable.SelectedRows) {
    target = (BudgetItem)row.DataBoundItem;
    BudgetList.Remove(target);
  }
  DtgTable.DataSource = null;
  DtgTable.DataSource = BudgetList;
}
private void btnClearAll_Click(object sender, EventArgs e) {
  BudgetTable.Rows.Clear();
}

private void btnClearAll_Click(object sender, EventArgs e) {
  BudgetList = new BindingList<BudgetItem>();
  DtgTable.DataSource = null;
  DtgTable.DataSource = BudgetList;
}
private void btnAddItem_Click(object sender, EventArgs e) {
  if (!AllFieldsEntered()) {
    MessageBox.Show("'ID', 'Type','Name', 'Expense' and 'Income' fields cannot be empty!");
  }
  else {
    StringBuilder errorString = new StringBuilder("Invalid Values: " + Environment.NewLine);
    bool noErrors = true;
    if (!int.TryParse(txtID.Text, out int id)) {
      errorString.AppendLine("ID must be a valid integer");
      noErrors = false;
    }
    if (!decimal.TryParse(expenseField.Text, out decimal exp)) {
      errorString.AppendLine("Expense must be a valid decimal");
      noErrors = false;
    }
    if (!decimal.TryParse(incomeField.Text, out decimal inc)) {
      errorString.AppendLine("Income must be a valid decimal");
      noErrors = false;
    }
    string date = dtpDate.Value.ToString("MM/dd/yyyy");
    if (noErrors) {
      BudgetTable.Rows.Add(id, date, cbbxType.Text, nameField.Text, exp, inc);
    }
    else {
      MessageBox.Show(errorString.ToString());
    }
  }
}
private void btnAddItem_Click(object sender, EventArgs e) {
   if (!AllFieldsEntered()) {
    MessageBox.Show("'ID', 'Type','Name', 'Expense' and 'Income' fields cannot be empty!");
  }
  else {
    StringBuilder errorString = new StringBuilder("Invalid Values: " + Environment.NewLine);
    bool noErrors = true;
    if (!int.TryParse(txtID.Text, out int id)) {
      errorString.AppendLine("ID must be a valid integer");
      noErrors = false;
    }
    if (!decimal.TryParse(expenseField.Text, out decimal exp)) {
      errorString.AppendLine("Expense must be a valid decimal");
      noErrors = false;
    }
    if (!decimal.TryParse(incomeField.Text, out decimal inc)) {
      errorString.AppendLine("Income must be a valid decimal");
      noErrors = false;
    }
    if (noErrors) {
      BudgetList.Add(new BudgetItem(id, dtpDate.Value, cbbxType.Text, nameField.Text, exp, inc));
      DtgTable.DataSource = null;
      DtgTable.DataSource = BudgetList;
    }
    else {
      MessageBox.Show(errorString.ToString());
    }
  }
}
private bool AllFieldsEntered() {
  if (string.IsNullOrWhiteSpace(cbbxType.Text) ||
      string.IsNullOrWhiteSpace(expenseField.Text) ||
      string.IsNullOrWhiteSpace(txtID.Text) ||
      string.IsNullOrWhiteSpace(incomeField.Text) ||
      string.IsNullOrWhiteSpace(nameField.Text)) {
    return false;
  }
  return true;
}
this.txtID.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.IntegerOnlyField_KeyPress);

this.expenseField.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.DecimalOnlyField_KeyPress);


this.incomeField.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.DecimalOnlyField_KeyPress);
private void DecimalOnlyField_KeyPress(object sender, KeyPressEventArgs e) {
  if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.')) {
    e.Handled = true;
  }
  TextBox txtDecimal = sender as TextBox;
  if (e.KeyChar == '.' && txtDecimal.Text.Contains(".")) {
    e.Handled = true;
  }
}
private void IntegerOnlyField_KeyPress(object sender, KeyPressEventArgs e) {
  if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back))) {
    e.Handled = true;
  }
}