上周在開發Winform 項目中,我曾遇到一個看似簡單,但一直都沒有解決的問題,那就是:設置winform DataGridView控件的行DefaultCellStyle,但卻沒有任何變化,我也曾求助于博問:http://q.cnblogs.com/q/72294/,但大家給的答案沒有一個能解決這個問題,可能是問題重現不太容易,我自己也曾多次在其它項目中嘗試重現這個問題,但一直都是正確的,沒有出現我當前項目的問題,簡直要崩潰啊!
先來看看我原有的代碼:
private void Form1_Load(object sender, EventArgs e) { dataGridView1.SetHeader<Zwj.TEMS.Entities.AssetDetail>(t => t.AssetSingleNo, t => t.BaseInfo.Name, t => t.BaseInfo.Category.CategoryName, t => t.Price, t => t.ProcureImport.Date, t => t.State.State); LoadData(); } private void LoadData() { var resultList = QueryBusiness<ProcureExport>.GetList(t =>true,//這里演示就直接忽略條件 t => new { t.AssetSingleNo, t.AssetSingleInfo.BaseInfo.Name, t.AssetSingleInfo.BaseInfo.Category.CategoryName, t.AssetSingleInfo.Price, t.AssetSingleInfo.ProcureImport.Date, t.AssetSingleInfo.State.State },t =>t.AssetSingleNo,1,10); dataGridView1.DataSource = resultList; int entityInListIndex = 1; dataGridView1.Rows[entityInListIndex].DefaultCellStyle = new DataGridViewCellStyle() { ForeColor = Color.Blue, Font = new Font("Arial", 11F, FontStyle.Bold) }; }
最終呈現的效果如下:
從上面的表格中可以看出,第2行(索引為1,實際為第2行)沒有任何效果。當然如果你將這些代碼及表格復制到其它項目中,可能不會出現這樣的問題,這就是很煩人的事情。為了解決這個簡單問題,搞清楚原因,今天一上班,我又開始進行測試與繼續在網上找答案,終于功夫不負有心人,終于在微軟的社區中發現有人也提到這樣的問題,并解決了,地址是:https://social.microsoft.com/Forums/zh-CN/d928e42d-9e10-4b1a-b2ee-2694894f47af/datagridview?forum=visualcshartzhchs,這里面提到:
重新把所有綁定的數據在顯示一遍,這里有一點延時,導致顏色其實沒有設置到正確顯示的row上。在DatabindingCompleted 時間里面,確保所有的數據 都已經綁定完成,這時候 能夠確保 設置在正確的 行上面。
問題原因找到了,原來是綁定后,數據有延遲,必須確認數據綁定完成后,才能進行樣式設置,基于這個原因,我修正了一下代碼,將原設置Style的代碼放到DataBindingComplete事件中,如下:
private void Form1_Load(object sender, EventArgs e) { dataGridView1.SetHeader<Zwj.TEMS.Entities.AssetDetail>(t => t.AssetSingleNo, t => t.BaseInfo.Name, t => t.BaseInfo.Category.CategoryName, t => t.Price, t => t.ProcureImport.Date, t => t.State.State); dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete); LoadData(); } private void LoadData() { var resultList = QueryBusiness<ProcureExport>.GetList(t =>true,//這里演示就直接忽略條件 t => new { t.AssetSingleNo, t.AssetSingleInfo.BaseInfo.Name, t.AssetSingleInfo.BaseInfo.Category.CategoryName, t.AssetSingleInfo.Price, t.AssetSingleInfo.ProcureImport.Date, t.AssetSingleInfo.State.State },t =>t.AssetSingleNo,1,10); dataGridView1.DataSource = resultList; } private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { int entityInListIndex = 1; dataGridView1.Rows[entityInListIndex].DefaultCellStyle = new DataGridViewCellStyle() { ForeColor = Color.Blue, Font = new Font("Arial", 11F, FontStyle.Bold) }; }
效果如下:
問題終于解決了,雖然是一個小問題,但若不明白原理及找到問題根源,小問題也會變成大問題,所以從這個問題中告誡我自己及大家:不要輕視任何一個問題,要有刨根問底的決心,每一個問題都要找到根本原因,不僅要知道如何做,還要明白為什么要這樣做,這樣才會成長。
文章列表