用DataGridView無分頁綁定一個幾千條數據的查詢,查詢的時候界面直接卡死十幾秒,用戶體驗非常不好,因此用異步操作解決界面卡死的問題
原本場景:點擊[查詢]后,界面直接卡死
優化場景:點擊[查詢]后,界面可以隨意移動,感覺不到后台在做大量數據的讀取和綁定
private void btnQuery_Click(object sender, EventArgs e) { // 查詢按鈕點擊后,按鈕文本由"查詢"改為"加載中",並把按鈕狀態改為不可點擊 btnQuery.Text = "加載中..."; btnQuery.Enabled = false; // 使用匿名方法定義一個委托事件,委托事件主要操作數據庫查詢,並返回查詢的結果,不涉及任何UI操作 Func<DataTable> act = () => { string sqlstmt = GetQuerySQL(); DbParams dbpara = new DbParams(DbFactory.Instance.ProviderName); dbpara.AddInputDateTime("@beginTime", dtpStart.Value); dbpara.AddInputDateTime("@endTime", dtpEnd.Value); DataTable dtUserList = DbFactory.Instance.ExecuteDataTable(sqlstmt, dbpara.ToArray()); return dtUserList; }; // 異步調用委托事件,在委托事件回調方法中,使用任意控件的異步方法把查詢結果綁定到數據表控件中 act.BeginInvoke((result) => { DataTable dtResult = act.EndInvoke(result); // this是當前WinForm窗口的實例,也可以替換為界面中的任意控件示例,如dgvMain.BeginInvoke this.BeginInvoke(new Action<DataTable>((DataTable dtList) => { dgvMain.DataSource = dtList; btnQuery.Text = "查詢(&Q)"; btnQuery.Enabled = true; }), dtResult); }, null); }
WinForm DataGridView顯示行頭序號代碼
this.dgvMain.RowPostPaint += (object sender, DataGridViewRowPostPaintEventArgs e) => { DataGridView dgv = sender as DataGridView; SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor); e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dgv.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 7); };
參考文章:
http://www.cnblogs.com/yuyijq/archive/2010/01/11/1643802.html
版權聲明:本文采用署名-非商業性使用-相同方式共享(CC BY-NC-SA 3.0 CN)國際許可協議進行許可,轉載請注明作者及出處。 |