user1863593
user1863593

Reputation: 199

C# - formatting numeric characters

I am working on a tutorial and having a slight issue with formatting on a web form. Seems that once my outputted numbers reach 2 digits that the alignment is off and shifts to the right. Any tricks to aligning numeric characters correctly?

Here is my code:

 private void btnDisplay_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= 10; i++)
        {
            lblProduct.Text += String.Format(i + "   ").PadRight(10);
            for (int j = 1; j <= 10; j++)
            {
                if (i > 0) lblProduct.Text += String.Format(i * j + "   ").PadRight(10);
                else lblProduct.Text += String.Format(j + "   ").PadRight(10);
            }
            lblProduct.Text += "\n";
        }
    }

Upvotes: 0

Views: 212

Answers (2)

egrunin
egrunin

Reputation: 25083

This is tabular data, it's why the <TABLE> tag was invented.

In your stylesheet:

<style>
.ProductTable
{
    text-align: right;
}
</style>

In your aspx file:

<asp:Table id="tblProduct" CssClass="ProductTable" runat="server">

In your code:

private void btnDisplay_Click(object sender, EventArgs e)
{
    for (int i = 0; i <= 10; i++)
    {
        TableRow tr = new TableRow();
        tblProduct.Rows.Add(tr);

        TableCell td = new TableCell();
        td.Text = i.ToString();
        tr.Cells.Add(td);

        for (int j = 1; j <= 10; j++)
        {
            td = new TableCell();
            tr.Cells.Add(td);
            td.Text = (i * j).ToString;
        }
    }
}

Upvotes: 1

D Stanley
D Stanley

Reputation: 152644

In general to left-justify and pad to 3 characters use:

String.Format("{0,-3}",i)

So for your case use

lblProduct.Text += String.Format("{0,-3}",i);
for (int j = 1; j <= 10; j++)
{
    if (i > 0) lblProduct.Text += String.Format("{0,-3}",i * j);
    else lblProduct.Text += String.Format("{0,-3}",j);
}
lblProduct.Text += "\n";

Upvotes: 2

Related Questions