我有一个任务来创建一个程序,该程序可以读取并保存更改的* .csv文件。因此,经过2周的构建,学习和尝试,我得到了下一个无法正常运行的代码。它正在阅读Okay,但我在“保存”按钮上苦苦挣扎。它具有“ System.NullReferenceException”错误。 //writer.Write(“,” + dataGridView1.Rows [i] .Cells [j] .Value.ToString()); -这是一行错误。error
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ITApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable table = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
//header names
table.Columns.Add("Item Code", typeof(string));
table.Columns.Add("Item Description", typeof(string));
table.Columns.Add("Item Count", typeof(int));
table.Columns.Add("On Order", typeof(string));
dataGridView1.DataSource = table;
}
//read file
private void btnOpen_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(@"C:\Stockfile\stocklist.csv");
string[] values;
for(int i = 1; i < lines.Length; i++)
{
values = lines[i].ToString().Split(',');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
table.Rows.Add(row);
}
}
//save file - problem
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog(); //streamwriter
sfd.Filter = "CSV Files (*.csv)|*.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(sfd.FileName))
{
for (int i = 0; i < dataGridView1.Rows.Count - 0; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
writer.Write("," + dataGridView1.Rows[i].Cells[j].Value.ToString()); //this line is broken =(
}
writer.WriteLine("");
}
writer.Close();
}
}
}
}
}