2015-03-13 94 views
2

我運動我與數據庫和數據綁定的第一步,而我試圖找出一些東西出來的字段。數據綁定控件屬性(例如顏色)不被顯示

在我Access數據庫中,我有一個表(Items)與字符串字段,如Description,CodeComments。我也有其他布爾字段,如AvailabilityRelevance

"Items" 

| ID | Description | Code | Comments | Availability | Relevance | 
|  |    |  |   |    |    |  
| 1 | Apple  | AP | Red  |  x  |    | 
| 2 | Orange  | OR | Orange |  x  |  x  | 
| 3 | Banana  | BN | Yellow |    |  x  | 
| 4 | Lime   | LM | Green  |  x  |    | 

我想在dataGridView通過數據綁定來顯示一些這方面的數據:多爲DescriptionCodeComments

private void DataBindGridView() 
    { 
     string dbPath = @"C:\FruitDB.accdb"; 
     string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbPath + ";Persist Security Info=False;"; 

     OleDbConnection dbConn = new OleDbConnection(connStr); 
     dbConn.Open(); 

     string query = "SELECT Description, Code, Comments, FROM Items ORDER BY ID ASC"; 
     OleDbCommand getItems = new OleDbCommand(query); 
     OleDbDataAdapter dbDataAdapter = new OleDbDataAdapter(getItems); 

     DataTable itemsTable = new DataTable(); 
     itemsTable.Locale = System.Globalization.CultureInfo.InvariantCulture; 
     dbDataAdapter.SelectCommand.Connection = dbConn; 
     dbDataAdapter.Fill(itemsTable); 

     // I want my first column to contain a checkbox for other purposes 
     // 
     DataGridViewCheckBoxColumn col1 = new DataGridViewCheckBoxColumn(false); 
     col1.Name = "Selection"; 
     col1.HeaderText = ""; 
     dataGridView1.Columns.Add(col1); 

     // Binding the dataGridView 
     // 
     dataGridView1.ReadOnly = false; 
     dataGridView1.DataSource = itemsTable; 

     // The user is allowed to edit the checkbox column only 
     // 
     foreach (DataGridViewColumn col in dataGridView1.Columns) 
     { 
      if (col.Index == 0) 
      { 
       col.ReadOnly = false; 
      } 
      else 
      { 
       col.ReadOnly = true; 
      } 
     } 
    } 

現在,即使我不想在dataGridView顯示AvailabilityRelevance信息作爲單獨的列,我想這些信息在一些其他的方式表現出來,例如作爲刪除線字體或將線條顏色設置爲灰色。

如何數據綁定這些屬性?我是否需要用不同的另一個查詢/命令/數據表重複整個事情...?

回答

1

我想你想是這樣的:

private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (dataGridView.Columns[e.ColumnIndex].Name == "Availability") 
     e.CellStyle.ForeColor = Color.Silver; 
} 

這基本上是所有繪畫細胞在Availability列灰色文本。你可以擴展代碼,只是爲了展示這個想法。

另外:當然,你一定要在您的SQL額外列。使用DataGridView來控制它們的外觀。您也可以完全隱藏列。

+1

謝謝,這個伎倆!我綁定了我的數據庫表中的所有列,然後爲不想顯示的列設置'column.Visible = false',然後使用cellFormatting事件。 – vi3x 2015-03-13 12:29:27