michael24B michael24B - 6 days ago 6
ASP.NET (C#) Question

ASP.NET C# BoundField format (Remove leading zeros)

How should DataFormatString of BoundField in Gridview look like that values won't have leading zeros?

So far I got this:

<asp:BoundField DataField="NUMBER" HeaderText="Id. number" DataFormatString="{0:d}">


Expected result:

000001 -> 1

002101 ->2101

I tried to figure that problem out with official documentation and this page. So far unsuccessful.

Answer

Another approach is to use String.Trim function. The following code is how I accomplished what you are trying to do:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Label runat="server" Text="<%#Eval(&quot;NUMBER&quot;).ToString().TrimStart('0')%>" ></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

The tricky part was using the correct combination of quotes and single quotes. You can use

&quot;

in place of the quote character around your datafield column that you are displaying.

Comments