Search code examples
asp.netgridviewoledb

How to add text to asp:BoundField in GridView?


I have the following GridView in which data is being fed from the OleDB Database.

<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server">
    <Columns>
        ...
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        ...
    </Columns>
</asp:GridView>

And I am reading the contents from the Database and printing in the GridView in the following manner:

protected void ShowGridView()
{
    string connectionString = GetConnString();
    OleDbConnection con = new OleDbConnection(connectionString);
    con.Open();
    string sqlQuery = "select * from ... ";
    OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
    showGridViewCommand.ExecuteNonQuery();

    DataTable dt = new DataTable();
    OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
    olda.Fill(dt);

    GridViewSavingsTracker.DataSource = dt;
    GridViewSavingsTracker.DataBind();

    con.Close();

}

What I want to do: I want to append % symbol to the contents of interestRate column in the GridView such that they should be displayed as 3% instead of 3. But the % symbol should not be inserted into the Database. In other words, the % symbol should only be used for display purposes in the GridView.


Solution

  • Depending on how you store the interest rate in the database will depend on which one of the below solutions remedy your question,

    If the interest rates are formatted such that 0 = 0% and 1 = 100% you can use:

    <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" DataFormatString="{0:p}"/>
    

    Documentation

    Otherwise you will need to do a template

    <columns>
        <asp:TemplateField HeaderText="Interest Rate:">
            <ItemTemplate>
                <asp:Literal ID="IntRate" runat="server" Text='<%# Eval("InterestRate") + "%" %>'></asp:Literal>
            </ItemTemplate>
        </asp:TemplateField>
    </columns>
    

    Updating answer as per comments below

    protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);
        var row = GridViewSavingsTracker.Rows[index];
        var interestRate = ((Literal row.FindControl("IntRate")).Text;
        if (e.CommandName == "SomeCommand")
        {
            TextBoxInterestRate.Text = interestRate;
        }
    }