今天突然要寫一些代碼,發現其中的一些一些控制項的使用很不靈活,現在我要把他們給積累起來,給我和需要的朋友一個方便!
不過呢,我現在還是一學生,如有高見請指教!
listbox
一.根據需要自己定義item的顏色
1.首先要設定其DrawMode屬性,設定DrawMode.OwnerDrawFixed 或 DrawMode.OwnerDrawVariable (有大小可變的項時使用)
2.實現其DrawItem事件響應
我寫的代碼如下:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
e.DrawBackground();
Brush myBrush = Brushes.Red;
Brush otherBrush=Brushes.Black;
if (e.Index == 2)
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
else
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, otherBrush, e.Bounds, StringFormat.GenericDefault);
}
註:e.DrawBackground(); 一定要寫哦,否則你都不知道自己選擇了哪個的!
dataGridView
一.設定行顏色
1、首先設定selectionMode為FullRowSelect
2、設定AllowUserToAddRows屬性為false(否則會發生索引錯誤的)
下面就是我寫的代碼了(省略了具體的應用設定,通過對.rows[e.RowIndex]的判斷就可以了):
DataGridViewCellStyle style = new DataGridViewCellStyle();
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
style.BackColor = Color.Red;
dataGridView1.Rows[e.RowIndex].DefaultCellStyle = style;
}