2

I have a problem that I busted my head for 7 days, so I decide to ask you for help. Here is my problem:

I read data from datagridview (only 2 cell), and fill all given data in stringbuilder, its actually article and price like invoice (bill). Now I add all what I get in stringbuilder in just string with intention to split string line under line, and that part of my code work but not as I wont. Article is one below another but price is one price more left another more right not all in one vertical line, something like this:

Bread  10$
Egg    4$
Milk   5$

My code:

string[] lines;
StringBuilder sbd = new StringBuilder();
foreach (DataGridViewRow rowe in dataGridView2.Rows)
{
    sbd.Append(rowe.Cells[0].Value).Append(rowe.Cells[10].Value);
    sbd.Append("\n");
}
sbd.Remove(sbd.Length - 1, 1);
string userOutput = sbd.ToString();
lines = userOutput.Split(new string[] { "\r", "\n" },    
StringSplitOptions.RemoveEmptyEntries);
1
  • 2
    Why wouldn't you just build lines[] directly? Commented Jan 24, 2013 at 20:15

2 Answers 2

1

You can use the Trim method in order to remove existing leading and trailing spaces. With PadRight you can automatically add the right number of spaces in order to get a specified total length.

Also use a List<string> that grows automatically instead of using an array that you get from splitting what you just put together before:

List<string> lines = new List<string>();
foreach (DataGridViewRow row in dataGridView2.Rows) {
    lines.Add( row.Cells[0].Value.ToString().Trim().PadRight(25) +
               row.Cells[10].Value.ToString().Trim());
}

But keep in mind that this way of formatting works only if you display the string in a monospaced font (like Courier New or Consolas). Proportional fonts like Arial will yield jagged columns.

Alternatively you can create an array with the right size by reading the number of lines from the Count property

string[] lines = new string[dataGridView2.Rows.Count];
for (int i = 0; i < lines.Length; i++) {
    DataGridViewRow row = dataGridView2.Rows[i];
    lines[i] = row.Cells[0].Value.ToString().Trim().PadRight(25) +
               row.Cells[10].Value.ToString().Trim();
}

You can also use the PadLeft method in order to right align the amounts

row.Cells[10].Value.ToString().Trim().PadLeft(10)
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried this String Split method ?

String myString = "Bread         ;10$;";

String articleName = myString.split(';')[0];
String price = myString.split(';')[1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.