将c#代码中的文本添加到gridview标签中

我需要在gridview上的itemtemplate中添加一个特定的文本…

现在我在gridview中有这个

  <asp:Label ID="lblTotal" runat="server" Text=''>    

在它所说的部分

 <asp:Label ID="lblTotal" runat="server" Text=''> 

我做了一个特定的文本,但它总是相同的文本(当然除了在Eval中)…但我需要从这个方法获得我需要的格式。

 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"]; } 

我使用此方法获取特定字符串并在标签上使用它(我在cs文件上的代码上分配它)..但在这种情况下…我必须在gridview的列上插入该文本…

如何获取该字符串值并将其插入templatefield / itemtemplate内的标签上?

代替 …

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

…使用

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

但是,这假定GetFormatoMoneda与Web表单属于同一类。 如果没有,那么你需要包括类名,例如

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

然后,您需要对GetFormatoMoneda进行更改以使用对象类型参数,例如

 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"]; } 

或者使用另一个带有object参数的方法并调用GetFormatoMoneda(十进制),传入正确的值,例如

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

在这种情况下你会使用

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

如果您想以编程方式执行此操作,则可以:

Default.aspx的:

          

Default.aspx.cs:

 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Generate fake data var data = Enumerable.Range(1, 20); //Give the data to the grid gvGrid.DataSource = data; gvGrid.DataBind(); } } protected void gvGrid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { //Find the control var lblTotal = (Label)e.Row.FindControl("lblTotal"); //Get the data for this row var data = (int)e.Row.DataItem; //Display the data lblTotal.Text = data.ToString(); } }