2016-06-11 83 views
1

我有一個DGV與如下預先定義的列,這裏是生成方法和結合法數據表到預定義DataGridView列

fixGridAlarm(dgvAlarmlar); 


public void fixGridAlarm(DataGridView gvw) 
    { 
     gvw.AutoGenerateColumns = false; 
     gvw.RowTemplate.Height = 75; 
     gvw.ColumnCount = 3; 
     gvw.Columns[0].Name = "No"; 
     gvw.Columns[0].Width = 60; 
     gvw.Columns[0].ReadOnly = true; 
     gvw.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 
     gvw.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; 
     gvw.Columns[1].Name = "Tarih/Saat"; 
     gvw.Columns[1].Width = 490; 
     gvw.Columns[1].ReadOnly = true; 
     gvw.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 
     gvw.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; 
     gvw.Columns[2].Name = "Açıklama"; 
     gvw.Columns[2].Width = 1195; 
     gvw.Columns[2].ReadOnly = true; 
     gvw.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 
     gvw.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; 

     BindAlarmlarGrid(); 

    } 


    public void BindAlarmlarGrid() 
    { 
     string CSVFilePathName = pathAlarms; 
     string[] Lines = File.ReadAllLines(CSVFilePathName); 
     string[] Fields; 
     DataTable dt = new DataTable(); 
     dt.Columns.Add(dgvAlarmlar.Columns[0].Name, typeof(int)); 
     dt.Columns.Add(dgvAlarmlar.Columns[1].Name, typeof(DateTime)); 
     dt.Columns.Add(dgvAlarmlar.Columns[2].Name, typeof(string)); 
     DataRow Row; 
     for (int i = 0; i < Lines.GetLength(0); i++) 
     { 
      Fields = Lines[i].Split(new char[] { ',' }); 
      Row = dt.NewRow(); 
      for (int f = 0; f < 3; f++) 
      { 
       Row[f] = Fields[f]; 
      } 
      dt.Rows.Add(Row); 
     } 
     dgvAlarmlar.DataSource = dt; 

當我給其DataSource作爲DataTable列旁邊添加到原始DGV我如何將它綁定在原始網格上而不是下一個?

+0

不要你必須調用'dgvAlarmlar.DataBind();''後= dgvAlarmlar.DataSource DT;' –

+0

它的winform不是asp.net @AlexW – CanESER

+0

即時通訊發現它很難看到什麼問題 –

回答

0

我解決我的問題,改變了我的結合方式類似,而不是使用DataTable

public void BindAlarmlarGrid() 
    { 
     string CSVFilePathName = pathAlarms; 
     string[] Lines = File.ReadAllLines(CSVFilePathName); 
     string[] Fields; 

     for (int i = 0; i < Lines.GetLength(0); i++) 
     { 
      Fields = Lines[i].Split(new char[] { ',' }); 
      dgvAlarmlar.Rows.Add(Fields); 
     } 
    } 
0

數據綁定需要你設置DataGridViewColumn.DataPropertyName屬性,如備註MSDN文檔的部分解釋:

當AutoGenerateColumns屬性設置爲true時,每列自動將其DataPropertyName屬性設置爲數據源中屬性或數據庫列的名稱e由DataSource屬性指定。此綁定也可以手動執行,這對於僅顯示數據源中可用的屬性或數據庫列的子集很有用。在這種情況下,將AutoGenerateColumns屬性設置爲false,然後手動添加每個DataGridViewColumn,將每個DataPropertyName屬性的值設置爲要顯示的數據源中的屬性或數據庫列。

您可以爲比如你原來的代碼工作是這樣的:

public void fixGridAlarm(DataGridView gvw) 
{ 
    // ... 
    for (int i = 0; i < gvw.Columns.Count; i++) 
     gvw.Columns[i].DataPropertyName = gvw.Columns[i].Name; 
    BindAlarmlarGrid(); 
} 
相關問題