日期:2014-05-18  浏览次数:21204 次

DataGridView中,用鼠标代替滚动条的问题
问题的详细描述:
  我用DataGridView显示数据库中的数据,但是出现了滚动条(水平和竖直),我想让滚动条消失,用鼠标来替代它的功能。最好鼠标的默认焦点在第一行(注意不是单元格,用一条线显示),鼠标滚动的时候,显示线跟着移动。请问代码怎么写?


------解决方案--------------------
C# code

        public void Form5_MouseWheel(object sender, MouseEventArgs e)
        {
            int index=dataGridView1.SelectedRows[0].Index;
            System.Drawing.Point p = PointToScreen(e.Location);
            if (WindowFromPoint(p.X, p.Y) == dataGridView1.Handle.ToInt32())
            {
                if (e.Delta == 120)
                {
                    if (index >= 1)
                    {
                        dataGridView1.Rows[index - 1].Selected = true;
                    }
                }
                else if (e.Delta < 0)
                {
                    dataGridView1.Rows[index + 1].Selected = true;
                }
                dataGridView1.Focus();
                this.dataGridView1.FirstDisplayedScrollingRowIndex = index;//始终显示选中的行
            }
        }

        private void dataGridView1_MouseEnter(object sender, EventArgs e)
        {
            this.MouseWheel += new MouseEventHandler(Form5_MouseWheel);
        }

------解决方案--------------------
C# code

//Form.designer.cs里面在datagridview的地方加入鼠标滚轮事件
this.dataGridView1.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.dataGridView1_MouseWheel);

        private void dataGridView1_MouseWheel(object sender, MouseEventArgs e)
        {
            int rowIndex = this.dataGridView1.CurrentRow.Index;
            this.dataGridView1.ClearSelection();

            if (e.Delta > 0)
            {
                if (rowIndex > 0)
                {
                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[rowIndex - 1].Cells[0];
                    this.dataGridView1.Rows[rowIndex - 1].Selected = true;
                }
                else
                {
                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[rowIndex].Cells[0];
                    this.dataGridView1.Rows[rowIndex].Selected = true;
                }
            }
            else
            {
                if (rowIndex < this.dataGridView1.Rows.Count - 1)
                {
                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[rowIndex + 1].Cells[0];
                    this.dataGridView1.Rows[rowIndex + 1].Selected = true;
                }
                else
                {
                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[rowIndex].Cells[0];
                    this.dataGridView1.Rows[rowIndex].Selected = true;
                }
            }
        }