最近項目裏要寫GDI+其中就有一個用外部ScrollBar代替 dataGridView1內部的ScrollBar的問題。c#
實現的方式是用自定義控件蓋住dataGridView內部的ScrollBar。this
本文主要講:scrollBar的使用,達到的效果如圖,外部的scrollBar可以和dataGridView或者系統的滾動條同樣精確的滾動,同樣精確的長度:.net
1 是dataGridView內部的滾動條,至關精確了,滾動到最右邊正好全部數據都能顯示出來,比例大概是: 拖動條的長度:scrollBar長度 = 顯示出的數據的長度:全部數據的長度。code
2.是我實現的外部的VScrollBar.基本知足上述的比例。blog
不須要這麼精確的,只須要知道ScrollBar的屬性以及如何簡單使用的請移步:事件
http://blog.csdn.net/truelove12358/article/details/17309143get
下面是實現的代碼:it
關鍵是如何設置屬性及滾動事件,io
private void InitScrollBar() { hScrollBar1.Dock = DockStyle.Bottom; int count = dataGridView1.ColumnCount; int gridWidth = 0; for (int k=0; k < count; k++) { gridWidth += dataGridView1.Columns[k].Width; } //關鍵代碼位置 hScrollBar1.Maximum = gridWidth; hScrollBar1.Minimum = 0; hScrollBar1.SmallChange = gridWidth / count; hScrollBar1.LargeChange = dataGridView1.Width - 5;//微調這裏的 5 this.dataGridView1.ScrollBars = ScrollBars.Both; //this.hScrollBarEx1.Scroll += new ScrollEventHandler(hScrollBarEx1_Scroll); this.hScrollBar1.Scroll +=new ScrollEventHandler(hScrollBar1_Scroll); } private void hScrollBar1_Scroll(object sender, ScrollEventArgs e) {//關鍵代碼位置 this.dataGridView1.HorizontalScrollingOffset = hScrollBar1.Value; Application.DoEvents(); }