Datagridview:如果Cell值符合条件,则创建新的文本文件

时间:2017-06-16 09:39:09

标签: c# .net datagridview

我创建了Datagridview如下图所示,第一列作为参考值。

1

我想基于First列值将所有行导出到文本文件。 每个Level=0都会使用filename= Level 0 Partnumber

创建新的文本文件

以下是我的代码,但此代码仅将所有数据保存在1个文本文件中。

SaveFileDialog sv = new SaveFileDialog();
sv.FileName = "";
sv.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (sv.ShowDialog() == DialogResult.OK)
{
    TextWriter writer = new StreamWriter(sv.FileName);
    writer.Write("Level\tPartnumber\tDescription");
    writer.WriteLine("");
    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        for (int j = 0; j < dataGridView1.Columns.Count; j++)
        {
            writer.Write(dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
        }
        writer.WriteLine("");
    }
    writer.Close();
    MessageBox.Show("Data Exported");
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

添加linq名称空间并尝试此

    List<product> prdList = new List<product>();
    private void SetValue()
    {
        product prd1 = new product
        {
            Level = 0,
            PartNumber = "Item A",
            Description = "Product"
        };
        product prd2 = new product
        {
            Level = 0,
            PartNumber = "Item b",
            Description = "batry"
        };
        product prd3 = new product
        {
            Level = 1,
            PartNumber = "Item1",
            Description = "Product"
        };
        product prd4 = new product
        {
            Level = 1,
            PartNumber = "Item2",
            Description = "Product"
        };
        product prd5 = new product
        {
            Level = 1,
            PartNumber = "Item3",
            Description = "Product"
        };
        prdList.Add(prd1);
        prdList.Add(prd2);
        prdList.Add(prd3);
        prdList.Add(prd4);
        prdList.Add(prd5);
    }

    private void CreateTextFile()
    {
        var newPrdList = prdList.GroupBy(x => x.Level).ToList();

        foreach (var levels in newPrdList)
        {
            TextWriter writer = new StreamWriter("D:\\Level" + levels.FirstOrDefault().Level + ".txt");
            writer.Write("Level\tPartnumber\tDescription");
            foreach (var level in levels)
            {
                writer.WriteLine("");
                writer.Write(level.Level.ToString() + "\t");
                writer.Write(level.Description + "\t");
                writer.Write(level.PartNumber + "\t");
                writer.WriteLine("");
            }
            writer.Close();
        }
    }