C# datagridview toolTip懸浮框顯示詳細內容
阿新 • • 發佈:2019-01-07
如圖所示,這是公司要我實現的需求。
我的本次採購數量是多個合同的和,所以我想在看這一條的時候顯示他們分別是哪個合同的,分別採購了多少。
第一拖一個tooptip控制元件實現Draw事件
給我們的控制元件設定下屬性
this.dgv_goodsSum.ShowCellToolTips = false; this.toolTip1.AutomaticDelay = 0; this.toolTip1.OwnerDraw = true; this.toolTip1.ShowAlways = true; this.toolTip1.ToolTipTitle = " "; this.toolTip1.UseAnimation = true; this.toolTip1.UseFading = true;
(不能漏哦!)
第二實現datagridview的兩個事件CellMouseEnter(滑鼠進入單元格時觸發)和CellMouseLeave(滑鼠離開單元格時觸發)
然後就是主要程式碼:如下
private void dgv_goodsSum_CellMouseLeave(object sender, DataGridViewCellEventArgs e) { this.toolTip1.Hide(this.dgv_goodsSum);//滑鼠移出單元格後隱藏提示 } private void dgv_goodsSum_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { //判斷選擇單元格是否有效 if (e.RowIndex < 0 || e.ColumnIndex < 0) { return; } this.toolTip1.Hide(this.dgv_goodsSum); int i = e.ColumnIndex;//獲取滑鼠停留的列索引 int ei = e.RowIndex;//獲取停留的行索引 if (i >= 0 && ei >= 0) { Point mousePos = PointToClient(MousePosition);//獲取滑鼠當前的位置 //獲取滑鼠停留的單元格中的值 string tip = this.dgv_goodsSum[3, ei].Value.ToString();//獲取合同號 這裡我寫的是死的,因為我只要它這一個值,當然大家如果想要獲取到每一列的值的話就把我的3改成i就夠了 string tip1 = this.dgv_goodsSum[4, ei].Value.ToString();//獲取物品號 string tips = "------------------------\n 物品編號:" + tip1 + " \n-------------------------\n"; string[] strs; strs = tip.Split(';'); for (int j = 0; j < strs.Length; j++) { string sql = "select b.contractNo,a.thispurchaseqty, a.inqty from purchase_contract b inner join purchase_contract_goods a on a.mainid = " + strs[j] + " and b.id = " + strs[j] + " and goodsNo = '" + tip1 + "'"; using (DataAdapter da = new DataAdapter()) { DataTable dt = new DataTable(); da.Text = sql; da.Fill(dt); tips += " 合同號:" + dt.Rows[0][0].ToString() + "\n採購數量:" + dt.Rows[0][1].ToString() + "\n實際入庫:" + dt.Rows[0][2].ToString() + "\n-------------------------\n"; } } this.toolTip1.Show(tips, this.dgv_goodsSum, new Point(mousePos.X - 700, ei * 20));//在指定位置顯示提示框
} } private void toolTip1_Draw(object sender, DrawToolTipEventArgs e) { e.Graphics.FillRectangle(Brushes.AliceBlue, e.Bounds); e.Graphics.DrawRectangle(Pens.Chocolate, new Rectangle(0, 0, e.Bounds.Width - 1, e.Bounds.Height - 1)); e.Graphics.DrawString(this.toolTip1.ToolTipTitle + e.ToolTipText, e.Font, Brushes.Red, e.Bounds); }
好吧!就這些
本人初學者,希望能給大家幫助,也希望大家能有更好的程式碼例子讓我也學習學習。