2012-08-22 52 views
3

我需要顯示將來自數據庫的混合「硬編碼」字符串和數據。具體而言,每個偶數列都包含不是來自數據庫的字符串值,每個奇數列都包含數據。所以第1列,例如,將包含值1到12從數據庫中,從而使前兩列看起來像這樣(和相同的模式重複幾次):是否可以使用交替的垂直列填充DataGridView?

00:00 BoundVal1 
00:15 BoundVal2 
. . . 
02:45 BoundVal12 

這可能嗎?

現在我正在使用一個TableLayoutPanel來做這件事,但是這個代碼的編碼有一點小巧(不是Steely Dan的參考)。

+0

是的,這是可能的 - 一切皆有可能。你試過什麼了?如果我從頭開始做這件事,我會把'硬編碼'的值放在數據庫中......不要以某種方式與綁定值相關聯嗎? –

+0

我沒有權限更改數據庫內容;但是,我想我可以轉換相關值(例如,「1」顯示爲「00:00」,「2」顯示爲「00:15」,...「96」顯示爲「23」 :45「,但是我的主要挑戰是如何讓這些值垂直顯示(以列爲單位),而不是傳統的水平(以行爲單位)。對於添加到TableLayoutPanel的動態創建的控件,它工作得很好,但已決定如果可能,請使用DataGridView代替。是否可以垂直呈現數據是主要問題 –

+1

請將您的解決方案作爲您自己問題的答案發布,而不是問題本身的更新。 – mclark1129

回答

0

我終於得到這個工作的基礎上,由穆罕默德·曼蘇爾代碼在http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/ca89a857-6e17-44a7-8cdb-90d64a0a7bbe

int RowCount = 12; 
Dictionary<int, string> PlatypusPairs; 

. . . 

private void button3_Click(object sender, EventArgs e) { 
    // Retrieve data as dictionary 
    PlatypusPairs = InterpSchedData.GetAvailableForPlatypusAndDate(oracleConnectionTestForm, 42, DateTime.Today.Date); 
    int ColumnCount = 16; 
    // Add the needed columns 
    for (int i = 0; i < ColumnCount; i++) { 
     string colName = string.Format("Column{0}", i + 1); 
     dataGridView1.Columns.Add(colName, colName); 
    } 

    for (int row = 0; row < RowCount; row++) { 
     // Save each row as an array 
     string[] currentRowContents = new string[ColumnCount]; 
     // Add each column to the currentColumn 
     for (int col = 0; col < ColumnCount; col++) { 
      currentRowContents[col] = GetValForCell(row, col); 
     } 
     // Add the row to the DGV 
     dataGridView1.Rows.Add(currentRowContents); 
    } 
} 

private string GetValForCell(int Row, int Col) { 
    string retVal; 

    if (Col % 2 == 0) { 
     retVal = GetTimeStringForCell(Row, Col); 
    } else { 
     retVal = GetPlatypusStringForCell(Row, Col); 
    } 
    return retVal; 
} 

private string GetTimeStringForCell(int Row, int Col) { 
    const int TIME_INCREMENT_STEP = 15; 
    var dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); 
    dt = dt.AddMinutes(((Col * (RowCount/2)) + Row) * TIME_INCREMENT_STEP); 
    return dt.ToString("HH:mm"); 
} 

private string GetPlatypusStringForCell(int Row, int Col) { 
    int multiplicand = Col/2; 
    string val = string.Empty; 
    int ValToSearchFor = (multiplicand * RowCount) + (Row + 1); 
    if (PlatypusPairs.ContainsKey(ValToSearchFor)) { 
     PlatypusPairs.TryGetValue(ValToSearchFor, out val); 
     if (val.Equals(0)) { 
      val = string.Empty; 
     } 
    } 
    return val; 
} 
1

您可以創建一個DataTable對象並將其設置爲DataGridView的DataSource。