I have this list view in csharp and would like the columns to fill the entire space but I cannot find that property. In the DataGridView there is a property called AutoSizeColumnMode is there such a property in the listView
You can do this,
YourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
YourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
EDIT
Since you wanted the columns to be equally sized, as #berkay mentioned, you could do this,
foreach (ColumnHeader column in YourListView.Columns){
column.Width = YourListView.Width / YourListView.Columns.Count;
}
The above code will read each column height and and divide the total width by the number of columns.
Try this,
foreach (ColumnHeader column in listView1.Columns){
column.Width = listView1.Width / listView1.Columns.Count;
}
Hope helps,
Related
I have a DataGridView in my WinForms application. Basically, I want to input some 2D data there or something like that. It means, that I want to have both columns named and rows named. And so I did. But then there was a problem. When it's fine with column names, the row names tend to be not visible. For example:
The code I use to somehow "beautify" the DataGridView:
private void BeautifyTable(TableView tableView)
{
foreach (DataGridViewRow row in tableView.Rows)
{
row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
foreach (DataGridViewColumn col in tableView.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
}
TableView is a class created by me, and it inherits from DataGridView.
So now my question would be: Is there a way to somehow make those row names/titles appear in a normal way (in this particular case those are: s0, s1, s2.., but they're like cut from the left side).
P.S Is there a good way to "stretch" the columns? I mean if I have f.e 10 columns they would fill the whole DataGridView width, but if I would add (I do this dynamically) 5, so there would be 15 columns, still they would fit, just the width of every column would decrease?
Increase the width of the row header:
dataGridView1.RowHeadersWidth =
dataGridView1.RowHeadersWidth * 2; // or another value
Try to hide those arrows by setting the RowHeadersVisible to False in the properties of the datagridview at the Form.cs [Design] or just simply add the code below.
Me.DataGridView1.RowHeadersVisible = False
I actually found the best answer by myself.
You can set the WitdthSizeMode also for row headers, like this:
tableView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
And that's the result:
So I have found that one can get the bound datatable row for a datagridview row, however, I am seeking to do the opposite. I have the following working code that sorts the datatable rows into an array sorted by a date field. I am then performing some logic to fill a value based on how much quantity is available. When the quantity available is less than the quantity required, I want to color the datagrid row to let the user know of the situation. How can I refer to the correct datagridview row at this point?
Update For Clarity : This is a winform using a datagridview. The code shown is on a "Match All" button. Its purpose is to match a Qty to Transfer value from a Qty Required cell up to an available quantity for the row's Item.
Dictionary<string, float> availableQtys = new Dictionary<string, float>();
DataView view = new DataView(dtStaged);
DataTable distinctItems = view.ToTable(true, "Item");
for (int i = 0; i < distinctItems.Rows.Count; i++)
{
availableQtys[distinctItems.Rows[i].Field<string>(0)] =
Controller.Instance.GetAvailableQty(distinctItems.Rows[i].Field<string>(0), ddl_SourceLocation.SelectedValue.ToString());
}
DataRow[] rowList = dtStaged.Select("", "Req Ship ASC");
foreach (DataRow row in rowList)
{
if (ddl_SourceLocation.SelectedValue.ToString().Trim() == row["Dest Site"].ToString().Trim())
continue;
if (availableQtys[row["Item"].ToString()] < Convert.ToSingle(row["Qty Required"]))
{
row["Qty to Transfer"] = availableQtys[row["Item"].ToString()];
availableQtys[row["Item"].ToString()] = 0.0f;
warnUser = true;
// HERE I want to set the color of the matching data grid row
}
// some other stuff
}
As far as I understand, you use WinForms. And you probably use DataGridView to display your data.
The best solution for you is to create custom cell template.
For instance you can inherit DataGridViewTextBoxCell, and override OnPaint method.
There are 'rowIndex', and 'value' among the parameters of OnPaint method.
This way your template will be able to consider data bound item and paint the cell accordingly.
Another solution is to manually update rows color every time your data changed.
Here is an example.
I have 3 columns in my DataGridView. What I am trying to do is have the first 2 columns auto fit to the width of the content, and have the 3rd column fill the remaining space.
Is it possible to do in WinForms? I am loading my data from an EF DataContext if that's any use. I have included an image of how it currently looks.
You need to use the DataGridViewColumn.AutoSizeMode property.
You can use one of these values for column 0 and 1:
AllCells: The column width adjusts to fit the contents of all cells in
the column, including the header cell.
AllCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column, excluding the header cell.
DisplayedCells: The column width adjusts to
fit the contents of all cells in the column that are in rows currently
displayed onscreen, including the header cell.
DisplayedCellsExceptHeader: The column width adjusts to fit the
contents of all cells in the column that are in rows currently
displayed onscreen, excluding the header cell.
Then you use the Fill value for column 2
The column width adjusts so that the widths of all columns exactly fills the display area of the control...
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
As pointed out by other users, the default value can be set at datagridview level with DataGridView.AutoSizeColumnsMode property.
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
could be:
this.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
Important note:
If your grid is bound to a datasource and columns are auto-generated (AutoGenerateColumns property set to True), you need to use the DataBindingComplete event to apply style AFTER columns have been created.
In some scenarios (change cells value by code for example), I had to call DataGridView1.AutoResizeColumns(); to refresh the grid.
This is my favorite approach...
_dataGrid.DataBindingComplete += (o, _) =>
{
var dataGridView = o as DataGridView;
if (dataGridView != null)
{
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView.Columns[dataGridView.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
};
Just change Property from property of control:
AutoSizeColumnsMode:Fill
OR By code
dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.Fill;
Not tested but you can give a try. Tested and working. I hope you can play with AutoSizeMode of DataGridViewColum to achieve what you need.
Try setting
dataGridView1.DataSource = yourdatasource;<--set datasource before you set AutoSizeMode
//Set the following properties after setting datasource
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
This should work
Try doing,
AutoSizeColumnMode = Fill;
public static void Fill(DataGridView dgv2)
{
try
{
dgv = dgv2;
foreach (DataGridViewColumn GridCol in dgv.Columns)
{
for (int j = 0; j < GridCol.DataGridView.ColumnCount; j++)
{
GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
GridCol.DataGridView.Columns[j].FillWeight = 1;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
To build on AlfredBr's answer, if you hid some of your columns, you can use the following to auto-size all columns and then just have the last visible column fill the empty space:
myDgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
myDgv.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None).AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
This is what I have done in order to get the column "first_name" fill the space when all the columns cannot do it.
When the grid goes to small the column "first_name" gets almost invisible (very thin) so I can set the DataGridViewAutoSizeColumnMode property to AllCells as the others visible columns. For performance issues it's important to set them to None before data binding it and set back to AllCells in the DataBindingComplete event handler of the grid. Hope it helps!
private void dataGridView1_Resize(object sender, EventArgs e)
{
int ColumnsWidth = 0;
foreach(DataGridViewColumn col in dataGridView1.Columns)
{
if (col.Visible) ColumnsWidth += col.Width;
}
if (ColumnsWidth <dataGridView1.Width)
{
dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
else if (dataGridView1.Columns["first_name"].Width < 10)
{
dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
}
public void setHeight(DataGridView src)
{
src.Height= src.ColumnHeadersVisible ? src.ColumnHeadersHeight : 0 + src.Rows.OfType<DataGridViewRow>().Where(row => row.Visible).Sum(row => row.Height);
}
Try this :
DGV.AutoResizeColumns();
DGV.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
At the moment I bind my datagridview in a following manner
relations = new CalculationsDataRelations();
bs = new BindingSource();
bs.DataSource = relations.Relations;
DgvRelations.DataSource = bs;
DgvRelations.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
DgvRelations.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
The potential problem I see here is what would happen if I change colums order or insert a column in relations.Relations object.
Is it possible to avoid situations like this and set properties of columns not by index ?
You can access columns by names. This will still be a subject to bugs if you change column names, but probablity is much lower.
you can get the right columns index using the column name of the datasource
Method to Find GridView Column Index by Name
Hello people :)
I want to bind my comboboxes to dgv cells . when dgv cells will be resize change size automaticli comboboxes size . and want to dock on above dgv cells
how can i make this?
Actually your problem is not cleared much.
Here I am adding another answer.
As you have said in one of your reply that you want to resize "yourComboboxColumn" on changing the size of "Products" Column
Put this Code: In the ColumnWidthChange event
if (DGV.Columns.Contains("yourColumn") && e.Column == dataGridView1.Columns["Products"])
{
DGV.Columns["yourColumn"].Width = e.Column.Width;
}
Edited:
To bind data of your combobox to ComboboxColumn do this
((DataGridViewComboBoxColumn) DGV.Columns["yourColumn"]).DataSource = cb.Items;
//"yourColumn" is the comboBoxColumn in DGV
// cb is the ComboBox which contains Items
Add Column of a type DataGridViewComboBox to DataGridView and bind it with your DataSource
To resize your Columns on Changing the size of DGV set AutoSizeColumnMode to Fill
DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
Edited:
In the ColumnWidthChange event of DGV put below code
foreach (DataGridViewColumn column in DGV.Columns) //DGV is your dataGridView
{
column.Width = e.Column.Width;
}