Changing Cell Values of DataGridView

2019-08-26 11:48发布

问题:

Suppose I have the following hypothetical table:

How can I make a DataGridView display the following?

Notice the values of Sick have changed.

I have tried the following to no avail:

var query = from c in Patients
            select new
            {
                c.Name,
                c.Sick == 1 ? "Yes" : "No"
            };

回答1:

You can use the DataGridView.CellFormatting event.

private void dataGridView1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Sick")
    {
        if (e.Value != null)
        {
            if (e.Value.ToString() == "1"
            {
                e.Value = "Yes";
            }
            else
            {
                e.Value = "No";
            }
            e.FormattingApplied = true;
        }
    }
}