C # put a condition for a column value in a DataGridView with DataSource

1

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

In a Children table, there is a SexString attribute 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 Sex column, the values 0 and 1 then appear. How can 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 researched calc fields but I was not successful. Thank you for your attention!

    
asked by anonymous 18.09.2015 / 22:03

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 are going to use to display the values.

In this case, the correct event is dataGridView.CellFormatting , which accepts a delegate of type DataGridViewCellFormattingEventHandler ". You can do this as follows:

Page_Load

dsFilhos.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

In the same font

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;
    }
}
    
19.09.2015 / 23:37