我可以将单位转换应用于gridview列吗?

时间:2012-11-20 21:29:20

标签: c# asp.net gridview

我的gridview中有一列显示从我的数据库表中提取的某些项目的总成本。但是,我的用户还在其帐户中附加了货币信息。我想要做的是根据个人用户的货币信息转换此列。我尝试过以下方法:

<asp:HiddenField id="currencyconvfactor" runat="server" />

<asp:TemplateField HeaderText="Total" SortExpression="Total">
    <ItemTemplate>
        <%# currencyconvfactor.Value %> //this is just a test. see below for the issue.
    </ItemTemplate>
</asp:TemplateField>

背后的代码

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            currencyconvfactor.Value = 12345 
            //i simplified retrieving the specific factor value here as I do some database commands to pull the specific value
    }

但是,我注意到模板字段列始终为空。这是否意味着网格视图是在页面加载事件之前生成的?如果是这样,我如何在第一页加载时执行列转换?更具体地说,如何访问转换因子以及时执行转换?

3 个答案:

答案 0 :(得分:1)

您可能希望使用RowDataBound事件来访问该列并执行您需要的任何计算:

<强>的.aspx:

<Columns>
    <asp:TemplateField HeaderText="Template Field">
        <ItemTemplate>
            <asp:Label ID="lblConvValue" Runat="server" /> 
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

<强>代码隐藏:

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Get the current row's data
        DataRowView rowView = (DataRowView)e.Row.DataItem;

        // Do your conversion
        var conv = int.Parse(rowView["valueToConvert"].ToString()); 
        var converted = conv * 12345; // Whatever conversion you want.

        // Set the value of the control in the ItemTemplate
        Label lblConvValue= (Label)e.Row.FindControl("lblConvValue");
        lblConvValue.Text = converted.ToString(); 
    }
}

答案 1 :(得分:1)

如果所有行都使用相同的货币换算系数,则可以执行以下操作。  ...

 <ItemTemplate>
    <%#GetCurrencyconvfactor()%>
 </ItemTemplate>

...

在后面的代码中定义一个返回值的方法

    public string GetCurrencyconvfactor()
    {
        //you can also pass in custID as an argument if each row uses different factor
        return "123"; // or get this from the user profile/settings 
    }

答案 2 :(得分:0)

定义值后,调用GridView.DataBind()