我有一个包含一些数据的* .csv文件。必须使用datagridview打开并保存它。问题是 - 文件保存后我有1列空。
请参阅图片了解更多详情
我需要第一列不为空,并将项目计数定义为int。
我需要将“Item Count”定义为int,否则它将不会排序正确。
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)
{
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;
}
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(); // split the current line using the separator
}
table.Rows.Add(row);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV Files (*.csv)|*.csv";
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(sfd.FileName))
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
writer.Write("," + dataGridView1.Rows[i].Cells[j].Value.ToString());
}
writer.WriteLine("");
}
writer.Close();
MessageBox.Show("Done!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
您正在每行的开头写一个逗号,因此第1列中有一个空白。
一个解决方案是:
for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
if (j>0) writer.Write(",");
writer.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
}