I\'m trying to mimic what every other tabular view does with the DataGridView control, but I can\'t seem to get the headers correct.
I want a blank header to the right o
While it doesn't answer your question, an alternative could be to set the AutoSizeColumnsMode to Fill.
After adding all your columns, you can add an extra column, set the following properties to:
AutoSizeMode = Fill;
HeaderText = ""
ReadOnly = true;
SortMode = NotSortable;
, handle the gridView CellPainting event
for this particular column by preventing the borders from being painted:
private void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex > -1 && e.ColumnIndex == dataGridView1.Columns.Count - 1)
{
e.AdvancedBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None;
e.PaintBackground(e.ClipBounds, false);
e.Handled = true;
}
}
and you'll get what you want.
Try this
Dim dt As New DataTable()
dt.Columns.Add("a")
dt.Columns.Add("b")
dt.Rows.Add(dt.NewRow())
dt.Rows.Add(dt.NewRow())
dt.Rows.Add(dt.NewRow())
dt.Rows.Add(dt.NewRow())
dt.Rows.Add(dt.NewRow())
dt.Rows.Add(dt.NewRow())
dt.Columns.Add(" ")
dt.AcceptChanges()
DataGridView1.DataSource = dt
DataGridView1.AutoSize = True
DataGridView1.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
DataGridView1.Columns(2).Resizable = DataGridViewTriState.False
IMO, the best (and most efficient) way to do this is by creating an extra column at the end, to allow it to "eat up" (or "take up") the space that isn't occupied by other columns. The way to do this is to set the AutoSizeMode property to Fill.
Here is some sample code:
DataGridView grid = new DataGridView();
DataTable data = new DataTable();
//add columns, rows, etc. to DataTable data
data.Columns.Add("This is the first column."); data.Rows.Add(data.NewRow());
//etc.
//Add EXTRA column:
data.Columns.Add(""); //blank header
//Save changes
data.AcceptChanges();
//Set datasource
grid.DataSource = data;
Now, you have the grid, with an extra blank column. We have to set the column to the right properties:
data.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; //Sets AutoSizeMode to fill, as explained above, for 2nd column
Also, as najameddine explained, you might want to set the following properties:
ReadOnly = true;
SortMode = NotSortable;
Essentially, you're creating a blank column that takes up the empty space.
P.S. I just noticed that surajitkhamrai has a very similar code sample, but mine is in C# - however, the concept stays the same.