2017-06-16 52 views
-1

我創建瞭如下圖所示的Datagridview,並將第一列作爲參考值。Datagridview:如果單元格值符合條件,則創建新的文本文件

1

我想所有的行根據一列值導出到文本文件。 每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"); 
} 

在此先感謝。

+0

嗯,你問用戶與該'SaveFileDialog'一個文件名,然後你寫的所有行與給定文件名的文件。這裏沒有驚喜。 – Waescher

+0

您的照片將創建多少個文件? –

+0

2將根據圖片創建文本文件。 Item A.txt&Item B.txt。謝謝 – xFactor

回答

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(); 
     } 
    } 
相關問題