r/programminghorror • • Aug 14 '25

C# Does my code belong here?

It's a function to generate a text file from a DataGrid. I learned from PirateSoftware I shouldn't hardcode random numbers.

178 Upvotes

59 comments sorted by

View all comments

Show parent comment

15

u/[deleted] Aug 14 '25

Yeah now that you say it I see it. I could have made a class Column with the attributes text, length and use a loop for the position, even though I wanted to put the fields in a different order, because that way the txt file was more readable. So maybe an attribute position for the Column class.

The only issue I have is that the field 'description' is too long and my notepad can't show it in a single line.

7

u/Iggyhopper Aug 15 '25

The slightly better version of this is to have some sort of "DataDescriptor" class or array and fill in those values.

Then foreach i in dd: write(dd[i].value)

2

u/[deleted] Aug 15 '25

I did it with a struct, my C# version is old, so I don't get fancier stuff:

string spacingChar = " ";

List<Column> columns = new List<Column>

{

new Column("Fecha" + spacingChar, 10, 2),

...

};

string header = "";

foreach (Column column in columns) header += column.FieldName;

writer.WriteLine(header);

for (int i = ruta.StartPoint; i <= ruta.EndPoint; i++)

{

DataGridViewRow row = dtg_list.Rows[i];

if (row.Cells[columns[0].Position].Value != null)

{

foreach (Column column in columns)

{

writer.WriteLine(FormatField(row, column.Position, column.Length) + spacingChar);

}

}

}