Sometimes my windows applications have a check box column or combo box. By clicking the check box or changing the combo box selected value, the desire is for the under lying data to be changed immediately. This is NOT what happens.
By adding a few lines of code to the DataGridView CurrentCellDirtyStateChanged event, the desired functionality happens.
First create a simple data class with two constructors. The parameter less constructor is used by the binding source. I use the other constructor for easy use.
public class Employee
{
private string _EmployeeId = "";
public string EmployeeId
{
get { return _EmployeeId; }
set { _EmployeeId = value; }
}
private string _LastName = "";
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _FirstName = "";
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private bool _Active = true;
public bool Active
{
get { return _Active; }
set { _Active = value; }
}
public Employee()
{
}
public Employee(string employeeId, string lastName, string firstName, bool active)
{
EmployeeId = employeeId;
LastName = lastName;
FirstName = firstName;
Active = active;
}
}
Next, add some objects to a list and bind the list to the data source in the load event of the program. Even when a database is available, using a list with a DataGridView/BindingSource is a fast, light weight solution.
private void Main_Load(object sender, EventArgs e)
{
colActive.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee("12345", "Jones", "Susan", true));
employeeList.Add(new Employee("12233", "Jackson", "Carl", true));
employeeList.Add(new Employee("34455", "Edwards", "Thomas", false));
employeeList.Add(new Employee("23231", "Stevens", "Henry", true));
employeeList.Add(new Employee("76112", "Smith", "Jacob", true));
employeeList.Add(new Employee("10120", "Davis", "Mary", false));
employeeList.Add(new Employee("10299", "Anderson", "Helen", true));
bsDirtyCell.DataSource = employeeList;
}
The grid is shown below. Click the check box, and the under lying data object is changed.
The code below checks to see if the column is the check box column. As you can see, I am in the habit of checking the CurrentCell for null. Many times it is null in events when I would never expect it to be null. I just got in the habit of always checking.
private void dgvDirtyCell_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvDirtyCell.IsCurrentCellDirty)
{
if (dgvDirtyCell.CurrentCell != null)
{
if (dgvDirtyCell.Columns[dgvDirtyCell.CurrentCell.ColumnIndex] == colActive)
dgvDirtyCell.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
}
Download source files - 13.4 Kb