Adjust the column width only when its content cant fit in - c#

I have form with DataGridView on it that displays data. Everything looks fine except when one of the columns content is wider then the column width. So I searched and found a line of code that I added to my Adjust_the DGV_width method so that columns width is adjusted
foreach (DataGridViewColumn col in zGrid1.Columns)
{
col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
It works nicely but it is ugly and I would prefer to keep the columns width as is except when there is content that cant fit in.
How can I programmaticaly find out what is the width of the content that cant fit columns width?
Here is how it looks now, but I prefer when there is more space in columns.

This can be easily achieved by checking the column width after setting it to autosize.
Example:
int myDefaultWidth = 100;
myDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
foreach ( DataGridViewColumn column in myDataGridView.Columns )
{
if ( column.Width < myDefaultWidth)
{
column.Width = myDefaultWidth;
}
}

Related

Auto Resize Rows Header Height in DataGridView

Based on this post, how can I automatically resize the rows header height. It is actually the first column with index -1.
I tried:
datagridview.AutoResizeColumnHeadersHeight ();
datagridview.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
datagridview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
Illustration:
datagridview.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayCells;
and
datagridview.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
are both not working for me (see illustration).
It fits well the columns from index 0 and up. But the column with index -1 is not being auto-resized as expected.

Why doesn't cell text alignment doesn't work in DataGridView in C#?

I want to make an input box and I have a DataGridView. But it does't work to align the text content of headers or cells.
My code to create DataGridView at runtime:
DataGridView CreateInputBox(int proc,int mac)
{
DataGridView databox = new DataGridView();
for (int i = 0; i < mac; i++)
{
databox.Columns.Add("col" + i, "M" + i);
databox.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
for (int i = 0; i < proc; i++)
{
databox.Rows.Add();
}
databox.AutoSize = true;
databox.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
return databox;
}
The result:
So how can I do the alignment for the header and cells?
If I understood correctly, the answer is here: Right align a column in datagridview doesn't work
And the problem is in the Sorting as when it’s enabled the DataGrid reserves some place for a sort glyph. So if you disable the sorting it should work as you expect:
this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
Adding this as an answer so everybody who will get here in the future will easily find the way to resolve the problem.
The code above is only to center the cells foreach column but not the header of each column.
Try to add this line in your "for" :
databox.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
Src: Changing DataGridView Header Cells' Text Alignment And The Font Size

Fix row height of every row in TableLayoutPanel

I'm working on Windows c#.
Firstly, the things those can not be change as my need are following:
The Size of TableLayoutPanel is fixed.
The Total # of columns are fixed.
Now, I want to set a fix height for all rows but as increasing the rows, if I set the RowStyle property to Percent with 100.0F then it works fine for 3 to 4 items, but after 4-5 items, the control on one row overwrites controls on another row.
I have searched for this so more but i'm not able to get the proper answer. I have also tried the AutoSize, Percent, Absolute properties of RowStyle, even though it is not working.
So what to do and how? How can I achieve this?
Ultimately, I want to do same like as DataGridView of Windows C#.
Thanks in advance....
I'm working on WinForms...the sample code is here..
int cnt = tableLayout.RowCount = myDataTable.Rows.Count;
tableLayout.Size = new System.Drawing.Size(555, 200);
for (int i = 1; i <= cnt; i++)
{
Label lblSrNo = new Label();
lblSrNo.Text = i.ToString();
TextBox txt = new TextBox();
txt.Text = "";
txt.Size = new System.Drawing.Size(69, 20);
tableLayout.Controls.Add(lblSrNo, 0, i - 1);
tableLayout.Controls.Add(txt, 1, i - 1);
}
tableLayout.RowStyles.Clear();
foreach (RowStyle rs in tableLayout.RowStyles)
tableLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
The label and textboxes are working fine for 4-5 #of rows but whenever the #of row(in this case, variable cnt in for loop) increases, the rows are overwriting each other that is one control overwrite to another...I had drag-drop the TableLayoutPanel control and created just one row and 2 columns manually.
So please tell me how to do it.
I'm still new to tableLayoutPanels myself, but I noticed that at the bottom of your code, you're Clearing all the rowstyles from the collection, then you're trying to iterate through them in your foreach loop.
You did this:
tableLayout.RowStyles.Clear(); //now you have zero rowstyles
foreach (RowStyle rs in tableLayout.RowStyles) //this will never execute
tableLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
Try this instead.
TableLayoutRowStyleCollection styles =
tableLayout.RowStyles;
foreach (RowStyle style in styles){
// Set the row height to 20 pixels.
style.SizeType = SizeType.Absolute;
style.Height = 20;
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Edit: I just realized that adding N rows doesn't add N rowstyles that you can iterate through. I think what's happening is that you're adding N rows, but none of them have a rowstyles.
I suppose you can Clear() the rowstyles, then just add N rowstyles similar to how you're already doing.
There are 2 ways to increase the row height of table layout panel.
Look into the following link :
https://social.msdn.microsoft.com/Forums/windows/en-US/d80db8e1-d6cc-48b8-957f-0f73263c6d4a/how-to-change-the-row-height-of-a-tablelayoutpanel-at-runtime?forum=winforms
It specifies by setting the YourTableLayoutPanel.RowStyles[index].Height int he code behind class.
The other way is to set the row height in the designer of your UI. Through UI, go into Rows properties of the panel, select the row and set the required height using percent or absolute

Listview items text is trucncated and doesn't show it all

I am usign a code a code like this and when the text gets long, it cuts it off and doesn't show the whole text :( In this aspect I want it to behave like a list box item. One line was for one item in the list box and didn't have this trucnacted text issue.
listView1.Scrollable = true;
listView1.View = View.Details;
listView1.HeaderStyle = ColumnHeaderStyle.None;
ColumnHeader header = new ColumnHeader();
header.Text = "MyHeader";
header.Name = "MyColumn1";
listView1.Columns.Add(header);
listView1.Items.Add("TooLongTextDoesntShow");
listView1.Items.Add("short");
listView1.Items.Add("abcd");
I think it is just easier to attach a picture of the issue. Please notice how it is not displaying full text of the highlighted item :(
Thanks for your help.
Just specify a column header width.
ColumnHeader header = new ColumnHeader();
header.Text = "MyHeader";
header.Name = "MyColumn1";
header.Width = listView1.Width //Same Width as Entire List Control
listView1.Columns.Add(header);
Alternative ways to do, is during the add.
You can make use of: ListView.ColumnHeaderCollection.Add
public virtual ColumnHeader Add(
string text,
int width //width of the header
)
Ok, I found a solution, please let me know if there are better ways of doing it too
AFTER adding items to list view is done, we should call this:
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
We take an example of ListView with 2 columns and resize on contents and then to minimum width.
// Auto resize of ListView Columns to minimum width
private int[] ColumnsWidth = { 35, 322 };
/// <summary>
/// Resize the columns based on the items entered
/// </summary>
private void ResizeColumns()
{
// Auto Resize Columns based on content
m_urlsListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
// Make sure to resize to minimum width
if (m_urlsListView.Columns[0].Width < ColumnsWidth[0])
{
m_urlsListView.Columns[0].Width = ColumnsWidth[0];
}
if (m_urlsListView.Columns[1].Width < ColumnsWidth[1])
{
m_urlsListView.Columns[1].Width = ColumnsWidth[1];
}
}
The content is being truncated because of (practically invisible) column. You can tell the ListView to adjust the column widths automatically:
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
You can just add a column and define its width according to your text size requirement. Moreover "Scrollable" property can be set to true if the actual width of the listview control is smaller
ListView_Column_Width_Image

DataGridView header alignment slightly to left even after setting it to MiddleCenter

I'm setting the following properties for a DataGridView in my C# project ...
sampleDataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
sampleDataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
But I notice that the heading's (i.e. text in header cell is offset slightly to the left, for some reason .. The data rows alignment in perfectly in center though ...
What can be causing this ?
It is because there is a sorting glyph (little arrow) for which the DataGridView reserves some space to show the sort order. If you want to disable the sorting glyph, set the SortMode on your column to NotSortable, and your text should then be centered.
Old topic,
i had this problem, and i found out that the problem was that i had the grid datasource-linked to my stuff, and when the columns where created they put the ALLOW SORT ON by default, which created the arrow down button to sort, and the text gets pushed to the left.
small fix to this is:
private void MyDataGridView_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
I had the same problem as you and it seems it's a framework issue: MS Connect
Figure out the glyph width without refection and supress when out of line:
In the following code I turn on and off sorting while autoadjusting column width to the column header text width. The difference in width between sorting on/off will reveal the width used by the column sort glyph.
As column looses the glyph when column width is set less than autoadjusted width I supress it by inserting symetric left and right column padings.
I also use a dictionary to store ColumnWidth events by datagridview instance to turn width events on and off while seting the width.
I call this crazy code both to autoadjust initial column widths and to manage the column header padings when user drags column widths.
void AdaptColumnHeaderText(DataGridViewColumn column, bool autoSize=false)
{
//Supress column width events
if (dataGridViewColumnWidthEventHandlers.ContainsKey(column.DataGridView))
{
dataGridView1.ColumnWidthChanged -= dataGridViewColumnWidthEventHandlers[column.DataGridView];
}
//Save initial column with as preferred
var w_preferred = column.Width;
if (
column.SortMode.Equals(DataGridViewColumnSortMode.Automatic) &&
column.HeaderCell.Style.Alignment.Equals(DataGridViewContentAlignment.MiddleCenter))
{
//remove all header padding
column.HeaderCell.Style.Padding = new Padding(0, 0, 0, 0);
//Fit column width to header text with AND sort glyph
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
//save column width sort enabled
var w_sort = column.Width;
//Fit column width to header text with NO sort glyph
column.SortMode = DataGridViewColumnSortMode.NotSortable;
//save column width when sort disable
var w_nosort = column.Width;
//Calculate width consumed by sort glyph
var w_glyph = w_sort - w_nosort;
//Nominal column width if glyph width applied left and right of header text
var w_nominal = w_glyph + w_nosort + w_glyph;
//Disable column width autosize
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
//Enable column autosorting
column.SortMode = DataGridViewColumnSortMode.Automatic;
//If autosize option - ignore preferred width and set to nominal
if (autoSize)
{
w_preferred = w_nominal;
}
//Pad depending on final column width
if (w_preferred >= w_nominal)
{
//Preferred width greater than nominal - pad left of text to balance width used by glyph
column.HeaderCell.Style.Padding = new Padding(w_glyph, 0, 0, 0);
}
else
{
//Two symetric glyphs will not fit - pad left and right to supress glyph
w_glyph = (w_preferred - w_nosort) / 2;
column.HeaderCell.Style.Padding = new Padding(w_glyph, 0, w_glyph, 0);
}
column.Width = w_preferred;
Console.WriteLine("name:{0}, glyph:{1}, w_preferred:{2}", column.Name, w_glyph, w_preferred);
}
//re-enable column width events
if (dataGridViewColumnWidthEventHandlers.ContainsKey(column.DataGridView))
{
dataGridView1.ColumnWidthChanged += dataGridViewColumnWidthEventHandlers[column.DataGridView];
}
}
You can add two spaces at the beginning of the column name to compensate the space reseved for the glyph.

Categories

Resources