DataGridView Colour certain cell in column - c#

I have a datagridview that has two columns, what i want to do is iterate over the rows and colour only the second row based on a condition, so far i have this:
foreach (DataGridViewRow row in dsgDataGrid.Rows)
{
var stock = Convert.ToInt32(row.Cells[1].Value);
if (stock == 0)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
if (stock >= 1 && stock <= 5)
{
row.DefaultCellStyle.BackColor = Color.LightSalmon;
}
}
That gets the entire row red (where the value is 0) but can anyone advise on how to only affect the cell in the second column based on the condition?
Thanks.

You can set the BackColor of a specific cell by using the Cells property of the DataGridViewRow with the desired index, for example:
row.Cells[2].Style.BackColor = Color.Red;
You can also use the name of column:
row.Cells["ColumnName"].Style.BackColor = Color.Red;

You'll be able to set the Color on a specific cell of a row with the following line of code:
row.Cells[1].Style.BackColor = Color.Red;
Or you could also loop through columns instead and set the color on each cell depending on the value of the cell your looking up.

Related

Change color of datagridview row depending on value C#

I have datagridview which is populated with 6 columns product id,product name,features,price,quantity and total price. All product with 0 quantity is automatically removed from the datagridview. My questions is how do I change color of the cell in "Quantity" if:
If quantity is less than 20 color orange
If quantity is less than 10 color red
Please bear with me as I am new to programming. I am required to do this for the inventory system we made for our capstone project.
Many thanks!
you must first foreach on data grid view rows like following :
foreach (DataGridViewRow Myrow in dataGridView1.Rows)
then foreach on cell
foreach(DataGridViewCell cell in Myrow.Cells)
and then convert cells data to int32 and then use DefaultCellStyle.BackColor
foreach (DataGridViewRow Myrow in dataGridView1.Rows)
{
foreach(DataGridViewCell cell in Myrow.Cells)
{ if (Convert.ToInt32(cell.Value)<10)
Myrow .DefaultCellStyle.BackColor = Color.red;
else if(Convert.ToInt32(cell.Value)<20)
Myrow.DefaultCellStyle.BackColor = Color.orange;
}
}

Datagridview correct row is selected but the arrow is still pointing at the first record

I have programmed my DataGridView so that when a new record is inserted, the selected index will change to that newly created record. But the arrow is still pointing at the first row. This is the LINQ code I use.
int selectedRowIndex = 0;
DataGridViewRow row = dataGridViewFtpServers.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells["Id"].Value.ToString().Equals(selectedId.ToString()))
.First();
selectedRowIndex = row.Index;
dataGridViewFtpServers.Rows[selectedRowIndex].Selected = true;
How can I point the arrow to my selectedRowIndex so that I don't get this:
The black triangle cursor follows the CurrentRow property.
The current row property is read only but as noted in msdn:
To change the current row, you must set the CurrentCell property to a
cell in the desired row.

Change color of specific part of DataGridView or entire column in C#

Is it possible to change the color of this part of a DataGridView by code?
If not, how can I change the color of the whole DataGridViewRow? I tried this code, but it does not change the color:
DataGridViewRow row = new DataGridViewRow();
row.DefaultCellStyle.BackColor = Color.Green;
row.DefaultCellStyle.ForeColor = Color.Green;
As information, my columns are DataGridViewComboBoxColumn
You can set the row colour by setting DefaultCellStyle property. In the following example we are iterating through each row and checking cell[0] value and if the condition is true then setting the row backcolor and forecolor
foreach (DataGridViewRow row in mydataGridView.Rows)
{
string RowType = row.Cells[0].Value.ToString();
if (RowType == "Some Value")
{
row.DefaultCellStyle.BackColor = Color.Green;
row.DefaultCellStyle.ForeColor = Color.Green;
}
}
if you means to say changing the blue background ,Blue background is the default color for a selected row in gridview. You can change this color within the properties window
Gridview1.DefaultCellStyle.SelectionBackColor = Color.Red; or Color.Transparent
Gridview1.DefaultCellStyle.SelectionForeColor = Color.Black; or Color.Transparent
but if you are refreshing grid view in very short duration say less than 1 sec duration in that case you have to change the default color of added rows cells in Gridview,(above senario will work fine for static grid view).
Gridview1.Rows[i].DefaultCellStyle.SelectionBackColor = Color.Red; or Color.Transparent
Gridview1.Rows[i].DefaultCellStyle.SelectionForeColor = Color.Black;or Color.Transparent

DataGridView AutoFit and Fill

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;

column value in datagridview

i use these following codes to get cell's value in datagridview.
these codes show me each cell has been clicked.
i want to use some codes just show me special column for example column with index 1 but these codes show me each which has been clicked. Imagine i just want to show column 1 with it's clicked cell. please help me to solve this
string str = dataGridView1.CurrentCell.Value.ToString();
Thanks in advance
So you're trying to get the data from the second column for every row?
int index = 1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[index];
// Do something.
}
Edit: Per your comment, you're trying to get the value of the second column when any cell in the row is clicked. Try this:
string str = dataGridView1[1, e.RowIndex].Value.ToString();

Categories

Resources