Hi @GuoLearn ,Welcome to Microsoft Q&A,
You can use DataGridViewCell to pick selected cell and then modify its background.
The key code is:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
DataGridViewCell cell = dataGridView1.SelectedCells[0];
cell.Style.BackColor = System.Drawing.Color.Red;
}
}
Below is my sample code:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace _8_14_x
{
public partial class Form1 : Form
{
// Declare a new BindingListOfT with the Part business object.
BindingList<Part> listOfParts;
private void InitializeListOfParts()
{
// Create the new BindingList of Part type.
listOfParts = new BindingList<Part>();
listOfParts.AllowNew = false;
listOfParts.AllowRemove = false;
// Raise ListChanged events when new parts are added.
listOfParts.RaiseListChangedEvents = true;
// Add a couple of parts to the list.
listOfParts.Add(new Part("Widget", 1234));
listOfParts.Add(new Part("Gadget", 5647));
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
InitializeListOfParts();
dataGridView1.DataSource = listOfParts;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
DataGridViewCell cell = dataGridView1.SelectedCells[0];
cell.Style.BackColor = System.Drawing.Color.Red;
}
}
private void Edit_button_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow.Index == -1)
return;
DataGridViewCell cell = dataGridView1.SelectedCells[0];
cell.Value = "123";
}
}
// A simple business object for example purposes.
public class Part
{
private string name;
private int number;
public Part() { }
public Part(string nameForPart, int numberForPart)
{
PartName = nameForPart;
PartNumber = numberForPart;
}
public string PartName
{
get { return name; }
set { name = value; }
}
public int PartNumber
{
get { return number; }
set { number = value; }
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.