I have a strange issue with a DataGridView on a WinForm. I can resize all columns via mouse, but for the rightmost I can only shrink and not increase the size.
This is by design. When you Click/Hold your mouse button, the mouse is captured and cannot leave the client area, with the effect of blocking the resize. You have to give it a push.
I tried not to P/Invoke to release the capture.
See if this works for you (of course if any AutoSize mode is set, nothing will happen).
private bool IsLastColumn = false;
private bool IsMouseDown = false;
private int MouseLocationX = 0;
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
var dgv = sender as DataGridView;
int lastColumnIndex = dgv.Columns.Count - 1;
//Check if the mouse pointer is contained in last column boundaries
//In the middle of it because clicking the divider of the row before
//the last may be seen as inside the last too.
Point location = new Point(e.X - (dgv.Columns[lastColumnIndex].Width / 2), e.Y);
if (dgv.GetColumnDisplayRectangle(lastColumnIndex, true).Contains(location))
{
//Store a positive checks and the current mouse position
this.IsLastColumn = true;
this.IsMouseDown = true;
this.MouseLocationX = e.Location.X;
}
}
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
var dgv = sender as DataGridView;
//If it's the last column and the left mouse button is pressed...
if ((this.IsLastColumn) && (this.IsMouseDown) && (e.Button == MouseButtons.Left))
{
// Adding the width of the vertical scrollbar, if any.
int cursorXPosition = e.X;
if (dgv.Controls.OfType().Where(s => s.Visible).Count() > 0)
{
cursorXPosition += SystemInformation.VerticalScrollBarWidth;
}
//... calculate the offset of the movement.
//You'll have to play with it a bit, though
int colWidth = dgv.Columns[dgv.Columns.Count - 1].Width;
int colWidthOffset = columnWidth + (e.X - this.MouseLocationX) > 0 ? (e.X - this.MouseLocationX) : 1;
//If mouse pointer reaches the limit of the clientarea...
if ((colWidthOffset > -1) && (cursorXPosition >= dgv.ClientSize.Width - 1))
{
//...resize the column and move the scrollbar offset
dgv.HorizontalScrollingOffset = dgv.ClientSize.Width + colWidth + colWidthOffset;
dgv.Columns[dgv.Columns.Count - 1].Width = colWidth + colWidthOffset;
}
}
}
private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
this.IsMouseDown = false;
this.IsLastColumn = false;
}