Reputation: 337
I'm creating Winform DataGridView programmatically. I need to create several different lists so I'm adding each column dynamically. The problem that I'm facing is when the sum of all the columns' width is greater than the DataGridView width. The horizontal scrollbar shows correctly, works correctly when I move it, but, when I press TAB to go to a cell that is outside of the DGV visible range, is not scrolling automatically. Below is how I´m setting the DGV, being "this" the DataGridView itself.
public DataGridViewCellStyle GridStyle()
{
// Set the column header style.
DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();
columnHeaderStyle.ForeColor = DataFormatting.RegularForeColor;
columnHeaderStyle.BackColor = DataFormatting.RegularBackColor;
columnHeaderStyle.Font = DataFormatting.FontBold;
return columnHeaderStyle;
}
public DataGridViewCellStyle GridStyleAlternate()
{
DataGridViewCellStyle oAlternas = new DataGridViewCellStyle();
oAlternas.BackColor = DataFormatting.AlternateBackColor;
oAlternas.Font = DataFormatting.Font;
return oAlternas;
}
public void GridFormat()
{
//Estilo de los cabezales de las columnas
this.ColumnHeadersDefaultCellStyle = GridStyle();
this.AlternatingRowsDefaultCellStyle = GridStyleAlternate();
// Formato del grid
this.AllowUserToAddRows = true;
this.AllowUserToDeleteRows = true;
this.AllowUserToOrderColumns = true;
this.AllowUserToResizeColumns = true;
this.AllowUserToResizeRows = false;
//this.BackgroundColor = SystemColors.ActiveBorder;
this.Font = DataFormatting.Font;
this.MultiSelect = false;
this.ScrollBars = ScrollBars.Both;
this.ShowCellErrors = false;
this.ShowEditingIcon = false;
this.ShowRowErrors = false;
//Set the edit mode to "on enter" so that when a cell gains focus it automatically enters editing mode
this.AutoGenerateColumns = false;
this.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells | DataGridViewAutoSizeRowsMode.DisplayedHeaders;
this.EditMode = DataGridViewEditMode.EditOnEnter;
this.RowHeadersVisible = true;
this.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect | DataGridViewSelectionMode.CellSelect;
Any help is appreciated.
Upvotes: 0
Views: 704
Reputation: 337
Finally found it.
protected override void OnCellEnter(DataGridViewCellEventArgs e)
{
base.OnCellEnter(e);
if (!this.CurrentCell.Displayed)
{
this.FirstDisplayedScrollingColumnIndex = e.ColumnIndex;
}
}
Even though it is an odd behavior. When, on columns creation, the sum of the widths of the columns is narrowest than the width of the DGV control, and then, I increase (manually with the mouse) the width of the columns going beyond the DGV width, it works fine, as expected. But, when the sum of the widths of the columns is widest, is when this piece of code is needed. Hope this helps someone, even if is not an elegant solution.
Upvotes: 1