Reputation: 339
I am working on a form application in C#, and I have been stuck with the width of DataGridView
.
What I want to achieve is:
DataGridView
horizontal field completely with the data by appropriately adjusting the column sizes, AND The problem is, I am not sure how many columns exist in the table to read data from.
I thought I have achieved requirement 1 and 2 with the following code:
for(int i=0; i<myDataGridView.Columns.Count; i++){
myDataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
However, I realized that this does not satisfy requirement 2. Where there is more column space needed, it fails to add a scroll bar. If there are more columns than a certain value, it hides some part of the columns and data cells. As you can see in the image below, the relationship column's "p" is hidden AND there is no scroll bar:
After some struggle, I noticed the following code succeeds in adding the scroll bar:
for(int i=0; i<myDataGridView.Columns.Count; i++){
myDataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
However, this code now does not satisfy my first requirement. It does add a scroll bar if more space for more columns is needed, but if there are only a few columns it leaves the unused area like the image below (the backcolor is black):
Now I am at a loss on how to achieve both requirements. One way satisfies only one requirement. Can someone please give me some advance on how to meet both requirements? Thank you!
Upvotes: 2
Views: 2587
Reputation:
You need to set the fillweight of each column and set their autosizemode to Fill
, and set their min width so they are not just forced to fit regardless of how many columns you have or how narrow the user makes the window.
myDataGridView.Columns[i].FillWeight = GetFillWeight(myDataGridView.Columns[i].Name);
myDataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
myDataGridView.Columns[i].MinimumWidth = (int) myDataGridView.Columns[i].FillWeight;
If you set the minimum width of the columns, and those add up to more than the width of the gridview, then the gridview will get a scrollbar.
I suggest to set the FillWeight, you have a function that actually sets it differently depending on what column it is. Something like
private float GetFillWeight(string FieldName)
{
switch (FieldName)
{
case "FirstName":
case "LastName":
case "City":
return 300;
case "Sex":
return 150;
case "Age":
return 100;
Upvotes: 2