Plazza Sele
Plazza Sele

Reputation: 319

Change text of a cell on dataGridView_CellFormatting

I have a Datagridview column with a value as int. I have a condition for the value status, if(status == 1) then change text to Active, else change text to Not Active.

Any help would be much appreciated.

private void bindListToGridView(List<Employee> list)
{
     // DataTable dt2 = convertListToDataTable(list);
     // more codes here.
     using (dt2)
     {
        // more codes here.
        dataGridView1.Columns[8].Name = "Status";
        dataGridView1.Columns[8].HeaderText = "Status";
        dataGridView1.Columns[8].DataPropertyName = "status";

       dataGridView1.DataSource = dt2;
     }
 }
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    string columnName = dataGridView1.Columns[e.ColumnIndex].Name;
    if (columnName == "Status")
    {
        int value = (int)dataGridView1.Rows[e.RowIndex].Cells["Status"].Value;
        if (value == 1)
        {
           // set the cell text = Active
        }
        else
        {
            // set the cell text = Not Active
        }
    }
}

Upvotes: 2

Views: 1617

Answers (1)

OhBeWise
OhBeWise

Reputation: 5454

To avoid changing the underlying integer value, you can set the cell's format to the desired text:

if (value == 1)
{
    dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Active";
}
else
{
    dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Not Active";
}

Or more easily, as LarsTech pointed out, just equivalently set:

e.Value = "Active";

This works because we are already in the CellFormatting event handler and the Value property of DataGridViewCellFormattingEventArgs is the formatted converted value.

Upvotes: 1

Related Questions