如何使用c#

时间:2016-10-05 02:59:06

标签: c# csv checkbox datagridview

我想添加一个带复选框的新列,我的数据来自csv文件并使用以下代码在datagridview中显示:

DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(\data.csv);

if (fileContent.Count() > 0)
{
    //Create data table columns
    dtDataSource.Columns.Add("ID);
    dtDataSource.Columns.Add("Data 1");
    dtDataSource.Columns.Add("Data 2");
    dtDataSource.Columns.Add("Status");

    //Add row data dynamically
    for (int i = 1; i < fileContent.Count(); i++)
    {
        string[] rowData = fileContent[i].Split(',');
        dtDataSource.Rows.Add(rowData);
    }
    if (dtDataSource != null)
    {
        dataGridView1.DataSource = dtDataSource;
    }
}

但我还需要验证复选框是否已选中,列是否为“状态”,它们的值必须更改为1,或者如果未选中该值,则必须在datagridview的每一行中为0。

示例:

ID,Data1,Data2,Status,checkbox
1,aaa,bbb,0,✓
2,ccc,ddd,1,(unchecked)
3,eee,fff,1,(unchecked)

单击“保存”按钮时,csv文件应如下所示:

ID,Data1,Data2,Status
1,aaa,bbb,1
2,ccc,ddd,0
3,eee,fff,0

我该怎么办?有任何想法吗? CSV文件对我来说有点困难。

谢谢!

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,不管怎样,谢谢......

这是代码:

string id;

        for (int i = 0; i < dataGridView1.RowCount; i++)   {
        String path = "\\registros.csv";

        List<String> lines = new List<String>();

        if (File.Exists(path))
        {
            using (StreamReader reader = new StreamReader(path))
            {
                String line;

                while ((line = reader.ReadLine()) != null)
                {
                    id = (string)dataGridView1.Rows[i].Cells[2].Value;
                    if (line.Contains(","))
                    {

                        String[] split = line.Split(',');

                        if (split[1].Equals(id) && (bool)dataGridView1.Rows[i].Cells[0].FormattedValue == true)
                        {

                            split[10] = "" + 1;
                            line = String.Join(",", split);

                        }

                        if (split[1].Equals(id) && (bool)dataGridView1.Rows[i].Cells[0].FormattedValue == false) 
                        {

                            split[10] = "" + 0;
                            line = String.Join(",", split);

                        }

                    }
                    lines.Add(line);
                }

            }

            using (StreamWriter writer = new StreamWriter(path, false))
            {
                foreach (String line in lines)
                    writer.WriteLine(line);
            }
        }
    }