DataGridViewCellStyle how to style button? - c#

I'm a beginner in C# and I'm trying to style a DataGridView button in Windows Forms.
I don't know how to, as example, remove the border from a button or change the hover color.
Many configurations that are on a normal button are missing in the DataGridView settings.
How can I achieve a full editable button inside DataGridView?

Datagridview works a little different than normal buttons,
but you can still edit several things in it if you search for the subproperties inside the properties. Let's go in a bit of detail:
DefaultCellStyle
Once you've selected your dataGridView, go to properties > RowTemplate. In there, you find something called DefaultCellStyle. if you press on the '...' at the right. then it'll open a popup that allows you to change some of the standard design of the Cells.
The same can also be applied to ColumnHeadersDefaultCellStyle, which is almost the same as DefaultCellStyle.
Columns
You can also go to Columns and add a new Column. After you've added a new column, you're also able to set several properties unique to that Column as well. You can even set all the cells in a Column to act as buttons!
Datagridview has certainely the access to customise, but most of them are divided in the cellstyles and column collections.
Changing the backcolor on hover
This in't as easily done as on a normal button, I did a search and came with this solution:
In properties, at the lightning button, you can see the events, there you can doubleclick on 'CellMouseMove' and add this. (Change the datagridview1 name eventually to be equall to yours)
private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Blue;
}
Then doubleclick the 'CellMouseLeave' event so it can revert the color.
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
}
I hope this has helped you further.

Related

how to control text color in datagridview

When I run my App first I fill my datagridview, then I loop over my rows and change the font color, everything works fine but when I sort my rows (clicking on the head of datagridview column) the font color is back to it's origin color.
After checking this subject I found about the attribute 'Default Cell Styles' - I need to know how to disable it on a specific column, I need my font color not to change.
CurrentCellChange Event allows you to provide new action once your datagridview's cell has changed, so basically:
private void DataGrid1_CurrentCellChanged(object sender, EventArgs e)
{
//your style code
}

visual studio c# DataGridView maintain background color after sort

I populated a DataGridView with a DataTable that contains plain text. Later, I set a specific cell's background color using:
grid.Rows[row].Cells[col].Style.BackColor = setColor;
This works fine until I click on the column sort button in the DataGridView. I would like to know if there is a way to maintain the background color after sorting, irrespective of the text value of the cell. Once I set that cell's background color, it will remember that background color after sorting.
I have seen other examples using the
CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
Event Handler, but the code they write here always seems to have a preconceived notion of what color the cell's background needs to be in relation to the cell's text content (ex: if cellText == "Critical" ...). That will not work in my case, I just need it to remember which cells are set to a specific color.
Any help?
Use the "DataBindingComplete" event !
e.g.
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
if (Convert.ToDateTime(row.Cells["Effective Date"].Value) > DateTime.Now)
{
row.DefaultCellStyle.BackColor = Color.LightYellow;
}
else { row.DefaultCellStyle.BackColor = Color.LightGreen; }
}
Here is what I had to do (thanks to the pointers from Sinatr) : I had to create a second DataTable that is used solely to keep track of which cells are what colors. Then, I had to add a hidden column to the DataGridView which is used as a key. I put the row number of the DataTable in this field so that after it gets sorted, I can use that row-number key to determine the row index into my Color Table. I added code in the DataGridView's CellFormatting to check the Color Table and reapply the color formatting. To make matters a little more complicated, I was having issues on getting the 1st column to become invisible, so I had to ensure that my hidden column was not the first column.
Overall I feel like these steps were hacks to get around the poorly designed and buggy DataGridView. I can't imagine a scenario where you would want to color a cell, and then have it revert colors after sorting. Sorting, in my mind, is just a rearrangement, NOT changing properties or values. I'm sure DataGridView is great and flexible for so many application, but this seems like a fundamental bug or design flaw.
I know this is a little old but the correct way to color DataGridView cells and maintain colors is to use the RowPrePaint event. That way you don't have to re-process the rows "manually" in any future changes to the DataGridView.
What I do is add additional columns or you can use a separate datatable to hold changes. Then using this event doing something similar to this:
private void dgvResults_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
bool.TryParse(dgvResults.Rows[e.RowIndex].Cells["IsChanged"].Value.ToString(), out bool bIsChanged);
if(bisChanged)
dgvUsers.Rows[e.RowIndex].Cells["MyCellName"].Style.BackColor = Color.Salmon;
}

Keypress event goes to the DataGridview instead of a cell

I have a DataGridView inside of the winform with delete event handled from toolstrip menu which delete the selected row (along with the object associated with that row in the DataGridView).
Now when i try to edit the value of any cell (to rename the object), and in the edit mode if i select some characters and press delete, it delete the row instead of deleting those selected characters.
What should i do to make the cell handle the event rather than the Winform.
snippets below:
this.deleteToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.Delete;
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.OnDelete);
private void OnDelete(object sender, EventArgs e)
{
}
try to check the properties of of your DataGridView SelectionMode, must not FullRowSelect
Found a solution :)
when i enter into edit mode i remove the delete key association
this.deleteToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.None;
and once i am done editing the cell in the OnAfterEdit i set it back to
this.deleteToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.Delete;
Hope it helps someone.

How to make a DataGridView column no-entry in VS2010/C#

I have a DataGridView which allows me to enter name/value pairs. The names are pre-defined, so the user just needs to enter a value.
I have made the name (the first) column read-only so it can't be changed - that's great, but it can still be selected, and indeed, is by default when the form is displayed.
Is it possible to make this (a) column no-entry, so it's not possible to select it? I think I've gone through all options in VS2010, and I've searched on Google but I can't even find someone else asking about it.
Many thanks
Ludwig
you can handle the selection by using the cell enter event and triggering an TAB press, this would mean that the particular is not selectable and instead the focus moves on to the next desired cell.
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns["NoSelect"].Index)
{ SendKeys.Send("{TAB}"); }
}

Background colour of DataGridViewCheckboxCell

I have a DataGridView bound to a list of objects, and I'm setting a dynamic cell background colour using the CellFormatting event, as in this answer. This works well for every column except the DataGridViewCheckboxColumn. When I click inside this cell (but outside the checkbox) the cell background changes to the default white.
Visually it looks like cell selection is occurring, despite my best efforts to stop it. My cell formatting code sets the SelectionBackColor as well as the BackColor. I've disabled cell selection using the CellStateChanged event, and none of the other columns are selectable:
private void PlayerGrid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.StateChanged == DataGridViewElementStates.Selected)
e.Cell.Selected = false;
}
Is there an extra workaround to override the cell behaviour for checkboxes?
I've found a workaround by adding the following code to the CellStateChanged event:
if (e.Cell is DataGridViewCheckBoxCell)
e.Cell.Style.BackColor = BackgroundColor(e.Cell.RowIndex);
(BackgroundColor() calculates the cell background colour based on the row.)
This cures the problem, but could cause performance issues for larger or virtual tables, by causing creation of extra style objects.
I rather like this approach for what I'm doing. It's able to agnostically change background color (including Checkbox) of ANY of the DataGridView cells with a mouse click or Tab--for example purposes--to highlight the currently selected cell. I found other approaches oddly did not color the background of the checkbox as other cell types were colored. In my example, I'm using this approach in the CellFormatting event but I believe a similar syntax can be duplicated with success elsewhere. Also, I believe this more closely answers the OPs question as it relates to, specifically, the CellFormatting event.
void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (W.mf.dgv.CurrentCell != null && e.RowIndex==W.mf.dgv.CurrentCell.RowIndex & e.ColumnIndex==W.mf.dgv.CurrentCell.ColumnIndex)
{
W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.YellowGreen;
}
else
{
W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = W.mf.dgv.DefaultCellStyle.SelectionBackColor;
}
}

Categories

Resources