2
我運動我與數據庫和數據綁定的第一步,而我試圖找出一些東西出來的字段。數據綁定控件屬性(例如顏色)不被顯示
在我Access數據庫中,我有一個表(Items
)與字符串字段,如Description
,Code
和Comments
。我也有其他布爾字段,如Availability
和Relevance
。
"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
通過數據綁定來顯示一些這方面的數據:多爲Description
,Code
和Comments
。
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
顯示Availability
或Relevance
信息作爲單獨的列,我想這些信息在一些其他的方式表現出來,例如作爲刪除線字體或將線條顏色設置爲灰色。
如何數據綁定這些屬性?我是否需要用不同的另一個查詢/命令/數據表重複整個事情...?
謝謝,這個伎倆!我綁定了我的數據庫表中的所有列,然後爲不想顯示的列設置'column.Visible = false',然後使用cellFormatting事件。 – vi3x 2015-03-13 12:29:27