首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >*.CSV文件中的表第一列为空

*.CSV文件中的表第一列为空
EN

Stack Overflow用户
提问于 2019-04-07 20:57:33
回答 1查看 434关注 0票数 0

我有一个包含一些数据的*.csv文件。它必须与datagridview一起打开和保存。问题是-在保存文件后,我有1列为空。

更多详情请参考图片

我需要第一列不为空,并定义项目计数为int。

我需要将"Item Count“定义为int,否则它将无法正确排序。

代码语言:javascript
复制
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);
                }
            }

        }
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-07 21:52:43

您在每一行的开头都写了一个逗号,因此第1列中有一个空格。

一种解决方案是:

代码语言:javascript
复制
for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
    if (j>0) writer.Write(",");
    writer.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55559241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档