2015-09-28 32 views
0

我有一個函數,導出我的Windows.Form應用程序DataGridView到CSV。 它工作正常,但問題是,我的DataGridView有兩行,每毫秒更新,但輸出到CSV沒有,它只是輸出的應用收盤後值...導出DataGridview到CSV每毫秒

public void writeCSV(DataGridView gridIn, string outputFile) 
    { 
     //test to see if the DataGridView has any rows 
     if (gridIn.RowCount > 0) 
     { 
      string value = ""; 
      DataGridViewRow dr = new DataGridViewRow(); 
      StreamWriter swOut = new StreamWriter(outputFile); 

      //write header rows to csv 
      for (int i = 0; i <= gridIn.Columns.Count - 1; i++) 
      { 
       if (i > 0) 
       { 
        swOut.Write(","); 
       } 
       swOut.Write(gridIn.Columns[i].HeaderText); 
      } 

      swOut.WriteLine(); 

      //write DataGridView rows to csv 
      for (int j = 0; j <= gridIn.Rows.Count - 1; j++) 
      { 
       if (j > 0) 
       { 
        swOut.WriteLine(); 
       } 

       dr = gridIn.Rows[j]; 

       for (int i = 0; i <= gridIn.Columns.Count - 1; i++) 
       { 
        if (i > 0) 
        { 
         swOut.Write(","); 
        } 

        value = dr.Cells[i].Value.ToString(); 
        //replace comma's with spaces 
        value = value.Replace(',', ' '); 
        //replace embedded newlines with spaces 
        value = value.Replace(Environment.NewLine, " "); 

        swOut.Write(value); 
       } 
      } 
      swOut.Close(); 
     } 
    } 

我調用的函數從SetDataGridView()函數我用它來更新DataGrids行每秒,但它仍然不會更新每個毫秒作爲DataGrid。

如何使DataGridView.Rows本身更新每毫秒更新CSV文件?

+1

爲什麼要更新每毫秒數據網格視圖在第一位?您沒有更新頻率爲1000 Hz的屏幕,因此您只能看到部分更新。 – Guffa

+0

我的意思是我更新每毫秒的行值... – ThisDude

回答

0

一個TargetUpdated事件添加到數據網格:

<DataGrid TargetUpdated="DataGrid_TargetUpdated" ... 

然後,在每個數據網格列定義設置NotifyOnTargetUpdated =真

<DataGridColumn Binding="{Binding Path=..., NotifyOnTargetUpdated=True, 
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/> 
在TargetUpdated處理程序調用writeCSV方法

然後:

private void DataGrid_TargetUpdated(object sender, DataTransferEventArgs e) 
{ 
     writeCSV(DataGridView,outputFile) 
} 
+0

雖然,列本身不會改變。但是,行確實是...... 這也適用於行或只更改列嗎? – ThisDude

+0

@ThisDude每列更改均爲行更改的結果。 –

+0

好的,謝謝... 但是,我認爲在這段代碼或您提供的解決方案中缺少一些東西...... 我沒有任何DataGrid定義。我所有的定義都是DataGridView。 – ThisDude

0

我解決它通過調用private void timer_0_Tick(object sender, EventArgs e)writeCSV(DataGridView,outputFile)被自動創建每當Timer類已被添加到一個C#應用程序... 而且,它開始更新CSV每次蜱更新DataGridView的