I have a datagridview in winform and would like to do two things. Resize the datagrid so that all columns are showen (no scrolls) based on the datagrid size resize the width of the winform.
tried the code below but it doesn't work*
int width = 0;
foreach (DataGridViewColumn col in information.Columns)
{
width += col.Width;
}
width += information.RowHeadersWidth;
information.ClientSize = new Size(width + 100,height);
Simple order of operations:
Set the AutoSizeColumnMode property of the DataGridView to AllCells.
Add the Width property of all the columns plus some slack for extra width from borders on the control, etc. (Maybe plus 2)
Set the Width property of the DataGridView to the width you calculated.
Set the form's Width to the Width of the DataGridView.
Up to you to actually code it.
EDIT: I am in front of a compiler now so I put this together:
Go into Visual Studio. Start a new Project. Don't put anything onto the form in the designer. Simply use this code in the initializer.
public Form1()
{
InitializeComponent();
// Create a DataGridView with 5 Columns
// Each column is going to sized at 100 pixels wide which is default
// Once filled, we will resize the form to fit the control
DataGridView dataGridView1 = new DataGridView();
for (int i = 0; i < 5; i++)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(col);
}
dataGridView1.Location = new Point(0, 0);
// Add the DataGridView to the form
this.Controls.Add(dataGridView1);
// Step 2:
// Figure out the width of the DataGridView columns
int width = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns)
width += col.Width;
width += dataGridView1.RowHeadersWidth;
// Step 3:
// Change the width of the DataGridView to match the column widths
// I add 2 pixels to account for the control's borders
dataGridView1.Width = width + 2;
// Step 4:
// Now make the form's width equal to the conbtrol's width
// I add 16 to account for the form's boarders
this.Width = dataGridView1.Width + 16;
}
This code creates a DataGridView with five columns and then sizes the control and the form exactly as you requested. I followed the exact steps I outlined above (except for step 1 because I don't have any data in my columns).
This code works. So if yours is NOT working, there must be something else silly that you have going on and I can't help you.
Hello I found out how to get this working using the following code below. information is the datagrid and this is the form.
int width = 0;
this.information.RowHeadersVisible = false;
for (int i = 0; i < information.Columns.Count; i++)
width += information.Columns[i].GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCells, true);
int rows = 0;
this.information.RowHeadersVisible = false;
for (int i = 0; i < information.Rows.Count; i++)
rows += information.Rows[i].GetPreferredHeight(i, DataGridViewAutoSizeRowMode.AllCells, true);
information.Size = new Size(width +20, rows+50);
this.Width = width + 50;
Related
I want the width of a DataGridView column after using FillWeight. Here is my code (C#, VS2015). I am trying to set textBox widths the same as dgv column widths. The last line of the code is my concern:
//Initialise dgv
//Set column widths for visual appeal
dgvPRD.Columns["INAME"].FillWeight = 200;
dgvPRD.Columns["IBATCH"].FillWeight = 150;
dgvPRD.Columns["DPQTY"].FillWeight = 100;
dgvPRD.Columns["IPUOMNAME"].FillWeight = 50;
dgvPRD.Columns["IQTY"].FillWeight = 100;
dgvPRD.Columns["INOTE"].FillWeight = 300;
//Initialise textBox locations and sizes
txtINAME.Left = this.Left + 41; //41 is the RowHeadersWidth of the dgv
txtINAME.Top = dgvPRD.ColumnHeadersHeight;
txtINAME.Width = dgvPRD.Columns["INAME"].Width; --> not working (it gives the original column width, before `FillWeight`)
I have a TableLayoutPanel, ug_degrees, with 3 columns and 1 row. Each cell gets dynamically populated with another TableLayoutPanel, degreePanel, containing 1 label and 1 textbox.
I need to get my layout to look something like this:
Right now my layout looks like this:
I'm at a loss for why I have those giant gaps between the cells, and why the row will not expand to fill its contents (a label & a textbox). I have tried to set the whole TableLayoutPanel's autosize property to true, but the columns get resized, even if I set only the rows' sizetype to autosize as well.
The properties behind the table shown are default. All non-default properties are customized in C# below.
// Dynamically load undergraduate degrees
int row = 0;
for (int i = 0; i < degrees.undergraduate.Count; i++) {
// Create and populate panel for each degree
TableLayoutPanel degreePanel = new TableLayoutPanel();
degreePanel.ColumnCount = 1;
degreePanel.RowCount = 2;
degreePanel.AutoSize = true;
foreach (RowStyle style in degreePanel.RowStyles) {
style.SizeType = SizeType.AutoSize;
}
degreePanel.BorderStyle = BorderStyle.FixedSingle;
//degreePanel.Margin = new Padding(0);
Label degTitle = new Label();
degTitle.Text = degrees.undergraduate[i].title;
degTitle.Dock = DockStyle.Fill;
TextBox degDesc = new TextBox();
degDesc.ReadOnly = true;
degDesc.Multiline = true;
degDesc.Dock = DockStyle.Fill;
degDesc.Text = degrees.undergraduate[i].description;
SizeF size = degDesc.CreateGraphics()
.MeasureString(degDesc.Text,
degDesc.Font,
degDesc.Width,
new StringFormat(0));
degDesc.Height = (int)size.Height;
degreePanel.Controls.Add(degTitle, 0, 0);
degreePanel.Controls.Add(degDesc, 0, 1);
ug_degrees.Controls.Add(degreePanel, i, row);
// Resize rows and columns (only after adding controls)
foreach (RowStyle style in ug_degrees.RowStyles) {
style.SizeType = SizeType.AutoSize;
}
// Jump to next row if current row is full
if ((i+1) % 3 == 0) {
row++;
}
Add degreePanel.Dock = DockStyle.Fill
I'm trying to create an autosizing button grid using a TableLayoutPanel. When I add columns at runtime with the following code they are not being sized evenly:
tableLayoutPanel.ColumnCount += 1;
for (var i = 0; i < tableLayoutPanel.RowCount; i++) {
var button = new Button {
Margin = Padding.Empty,
Padding = Padding.Empty,
Dock = DockStyle.Fill
}
tableLayoutPanel.Controls.Add(button);
}
The initial form with 1 column:
Adding a 2nd column:
Adding a 3rd column:
Is there a way to make the columns autosize evenly without manually calculating the dimensions?
It's necessary to explicitly reset the column styles:
private void RecalculateColumnStyles()
{
var cols = tableLayoutPanel.ColumnCount;
var pct = (float) 100 / cols;
tableLayoutPanel.SuspendLayout();
tableLayoutPanel.ColumnStyles.Clear();
for (var i = 0; i < cols; i++) {
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, pct));
}
tableLayoutPanel.ResumeLayout();
}
I'm writing a Winform application that processes a grid of products printed on a sheet. To more effectively communicate with my end user I've been tasked with creating a visual representation of the grid (as opposed to just giving them "Row x Col y in text" ) to depict which items on the sheet could not be processed.
My first thought was to use a grid of images (green check mark/red X) aligned in a grid to match the sheet that the app will actually process. The problem with that approach is that eventually we'll have different jobs that use different sheet alignments. One might be a 3x10 grid, another might be a 1x8 etc.
Is there something I can use to define an area of my form as reserved for images, and also a way to insert copies of my image file that have been resized to fit in that area?
Something like:
container.add(
new Image("myFileLocation", imgHeight, imgWidth),
(container.height / numRows),
(container.width/numCols)
);
?
Sorry if this is a stupid question. I'm comfortable in c# but have approximately zero experience designing GUIs for these things.
#ASh that's exactly what I wanted, thanks.
In case it helps anyone else out there here are some references that I found useful to learn how to use TableLayoutPanels:
Generate rows/columns at runtime.
TableLayoutPanel rows & columns at runtime
Add image file to picturebox
Set image source to picturebox which is added dynamically to Table Layout Panel
Resize image inside picturebox (stretch to fill)
Fit Image into PictureBox
Center images inside cells
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control
My code:
int rows = 7; //Will come from database
int cols = 3; //Will come from database
int colWidth;
int rowHeight;
PictureBox pbox;
Random rnd = new Random();
colWidth = 100 / cols;
if (100 % cols != 0)
colWidth--;
rowHeight = 100 / rows;
if (100 % rows != 0)
rowHeight--;
tabLP.Controls.Clear();
tabLP.ColumnStyles.Clear();
tabLP.RowStyles.Clear();
tabLP.ColumnCount = cols;
for (int i = 0; i < rows; i++)
{
tabLP.RowStyles.Add(new RowStyle(SizeType.Percent, rowHeight));
for (int j = 0; j < cols; j++)
{
tabLP.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, colWidth));
if (rnd.NextDouble() > 0.5 )
{
pbox = new PictureBox() { Image = Properties.Resources.red_X};
}
else
{
pbox = new PictureBox() { Image = Properties.Resources.checkbox_green };
}
pbox.Dock = DockStyle.Fill;
pbox.SizeMode = PictureBoxSizeMode.StretchImage;
tabLP.Controls.Add(pbox, j, i);
}
}
How to find how many columns and rows arranged by flowlayoutpanel.
FlowLayoutPanel panelstandard = new FlowLayoutPanel();
panelstandard.Size = new Size(1130,150);
panelstandard.Location = new Point(20, 250);
panelstandard.BorderStyle = BorderStyle.FixedSingle;
panelstandard.FlowDirection = FlowDirection.LeftToRight;
You can count it yourself:
int row = 0;
int column = -1;
int left = panelstandard.Controls[0].Left;
foreach(Control control in panelstandard.Controls)
{
// as soon as wrap occurs
if(control.Left < left)
{
// new row
row++;
column = 0;
}
else
column++;
left = control.Left + control.Width; // next control expected left
// here you know [row; column] of the control
}
// here you know total rows and columns
This doesn't take care about control Margin and possibly will not work if you use Dock and/or Anchor, but should work in the general case