Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,927 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi ,
i have a datagridview which is load of some data . how do i change all the cells forecolor within a row when a row is selected and revert it back when it is unselected .
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public partial class MainForm : Form
{
public MainForm()
{
DataTable table = new DataTable();
table.Columns.Add("Column1");
table.Columns.Add("Column2");
table.Columns.Add("Column3");
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
table.Rows.Add(Enumerable.Range(1, table.Columns.Count).Select(_ => rnd.NextDouble().ToString()).ToArray());
}
DataGridView dgv = new DataGridView();
dgv.DataSource = table;
dgv.Dock = DockStyle.Fill;
this.Controls.Add(dgv);
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.DefaultCellStyle.ForeColor = Color.Black;
dgv.DefaultCellStyle.BackColor = Color.White;
dgv.DefaultCellStyle.SelectionBackColor = Color.LightYellow; //dgv.DefaultCellStyle.BackColor
dgv.DefaultCellStyle.SelectionForeColor = Color.Green;
dgv.CellPainting += Dgv_CellPainting;
}
private void Dgv_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected)
{
if (e.ColumnIndex == dgv.CurrentCell.ColumnIndex && !dgv.IsCurrentCellInEditMode)
{
e.Graphics.FillRectangle(Brushes.LightPink, e.CellBounds);
e.Paint(e.CellBounds, e.PaintParts & ~DataGridViewPaintParts.Background);
e.Handled = true;
}
}
}
}
[2023-12-23T22:00Z+09:00] remove unnecessary code