C# set a condition for a column value in a Datagridview with Datasource

Asked

Viewed 215 times

1

I’m using VS2013 Entity 5. The situation is as follows:

In a table of Sons, there is an attribute sexFile that receives the value 0, 1. 0 for male and 1 for female. (could use "m" or "f", but it is a learning situation)

In my Datagridview, in the column Sex appear, then, the values 0 and 1. How could I put a condition so that instead of these values, "M" or "F appear"?

dsFilhos.Tables("filhos").Columns("sexoFilho").Expression ="IIF(sexoFilho='0', 'M', 'F')";

I searched on Calc Fields but was not successful. Thank you for your attention!

  • 1

    You can put in your question how is the code so far?

  • Edited code. I’m using that code, but it claims to be a "circular reference"

1 answer

1


If you talked about CalcFields, apparently you came from Delphi. In Webforms, things are not so different. What changes is the event you will use to display the values.

In this case, the correct event is the dataGridView.CellFormatting, who accepts a delegate of the kind DataGridViewCellFormattingEventHandler. You can do it this way:

Page_Load

dsFilhos.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

At the same source

void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dsFilhos.Columns[e.ColumnIndex].Name == "sexoFilho")
    {
        if (e.Value == null)
            return;

        string stringValue = (string)e.Value;
        stringValue = stringValue.ToLower();

        switch (stringValue) {
            case "m":
                e.Value = "Masculino";
            case "f":
                e.Value = "Feminino";
            default:
                e.Value = "Indefinido";
        }

        e.FormattingApplied = true;
    }
}
  • 1

    Perfect! Thank you very much! It worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.