如何:設定 Windows Form DataGridView 控制項的替代資料列樣式
表格式資料通常會以類似 Ledger 的格式呈現給使用者,在這種格式中,交替資料列會有不同的背景色彩。 這種格式可讓使用者輕鬆地指出每個資料列中有哪些儲存格,特別是具有許多資料行的寬資料表。
利用 DataGridView 控制項,您可以指定替代資料列的完整樣式資訊。 這個控制項可讓您使用背景色彩以外的樣式特性 (例如前景色彩和字型),來區分替代資料列。
在 Visual Studio 中會支援這項工作。 另請參閱 如何:使用設計 工具設定 Windows Forms DataGridView 控制項的替代資料列樣式。
以程式設計方式設定替代資料列樣式
設定由 DataGridView 的 RowsDefaultCellStyle 和 AlternatingRowsDefaultCellStyle 屬性所傳回之 DataGridViewCellStyle 物件的屬性。
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
With Me.dataGridView1 .RowsDefaultCellStyle.BackColor = Color.Bisque .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End With
注意
使用 RowsDefaultCellStyle 和 AlternatingRowsDefaultCellStyle 屬性所指定的樣式,會覆寫在資料行和 DataGridView 層級上所指定的樣式,但會由在個別資料列和儲存格層級設定的樣式所覆寫。 如需詳細資訊,請參閱 Windows Forms DataGridView 控制項 中的儲存格樣式。
編譯程式碼
這個範例需要:
名為
dataGridView1
的 DataGridView 控制項。System、System.Drawing 和 System.Windows.Forms 組件的參考。
穩固程式設計
若要達到最大延展性,您應該在使用相同樣式的多個資料列、資料行或儲存格之間共用 DataGridViewCellStyle 物件,而不是分別設定每個項目的樣式屬性。 如需詳細資訊,請參閱 調整 Windows Forms DataGridView 控制項 的最佳做法。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應