Zone007
Zone007

Reputation: 1

How to set the width of columns in datagridview

I have a datagridview and few testbox. User types in the details into the text box and when pressed enter it adds to the datagridview. Now the question is user will be allowed to save the rows into a text file but it in not saving in a proper format ie i am getting as:

Quantity  Name  Rate
--------------------
12 wers 30
2323 ertd 40

But i want it to save like this

Quantity  Name  Rate
--------------------
12        wers  30
2323      ertd  40

Any ideas in vb.net ??? plz help me out

Upvotes: 0

Views: 1541

Answers (1)

manji
manji

Reputation: 47968

You want to create a Fixed Column Width Text File, right?

You are separating cell values by a space, but you need to format them before to have for a given column same width (in chars) for all of it's cells.

To do that for column1 for example:

  • calculate the max width that can fit to all of it's cells (or choose some values that you know will not be exceeded).
  • use String.Format function to pad(left or right) the cell string with the exact space chars you need:

suppose max column1 width = 50; getting a 50-chars string of it's 1st cell:

string cellValue = String.Format("{0, -50}", dataGridView1.Rows[0]
                                            .Cells[0]
                                            .Value.ToString());

// -50 tells the format function to return a string with a length >= 50, 
// but because you calculated this value to fit to all cells, 
// cellValue.Length is 50.
// Spaces are added to the right,(50 instead of -50 to add spaces to the left)

Upvotes: 1

Related Questions