Search code examples
c#asp.netgridviewlabelitemtemplate

Add text from c# code to a gridview label


I need to add an specific text in an itemtemplate on a gridview...

right now I have this in my gridview

<asp:TemplateField HeaderText="Total" SortExpression="Total" ItemStyle-Width="100px">
    <ItemTemplate>
        <asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
        </asp:Label>
    </ItemTemplate>
</asp:TemplateField>

in the part where it says

<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>

I made an specific text, but it will always be the same text (well except in the Eval of course)... But I need to get the format I need from this method.

public static string GetFormatoMoneda(decimal decCantidad)
{
    //Get data from currency (Dollars, Pesos, Euros, etc.)
    DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);

    return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}

I use this method to get a specific string and use it on labels (I assign it on code on the cs file).. But in this case... I have to insert that text on the column of a gridview...

How can I get that string value and insert it on a label inside of a templatefield/itemtemplate??


Solution

  • Instead of ...

    Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'
    

    ...use

    Text='<%#GetFormatoMoneda(Eval("Total"))%>'
    

    However, this assumes that GetFormatoMoneda is in the same class as the web form. If not, then you need to include the class name, e.g.

    Text='<%#MyClass.GetFormatoMoneda(Eval("Total"))%>'
    

    Then you either need to make a change to GetFormatoMoneda to use an object type parameter, e.g.

    public static string GetFormatoMoneda(object objCantidad)
    {
        var decCantidad = Convert.ToDecimal(decCantidad);
    
        //Get data from currency (Dollars, Pesos, Euros, etc.)
        DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
    
        return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
    }
    

    or use another method with an object parameter and call GetFormatoMoneda(decimal), passing in the correct value, such as

    protected string CorrectFormat(object obj)
    {
        return GetFormatoMoneda(Convert.ToDecimal(obj));
    }
    

    in which case you would use

    Text='<%#CorrectFormat(Eval("Total"))%>'