Thursday, 26 July 2007

Gridview

Was looking for a way to populate a Gridview with a simple array of strings, and everybody and their dog seems to be posting tutorials about doing it with SQL data sources, etc (Or maybe I'm just really hopeless at Googling information I need). And then I found this gem of a guide on Gridview by Mike Pope. Turns out the feature I needed is apparently undocumented (go figure), and if you go over to his site here, you'll find, in his words:

"Sometimes your life is even simpler -- you have an array with simple values in it, and you want to display those. It's easy enough to bind the grid to the array. But how do you bind a BoundField to the contents of the array element? Turns out that if you set the DataField property of a BoundField to !, it tells the field (column) to get the ToString() version of whatever's in the array. (I'm pretty sure this is undocumented, though perhaps not unknown.)"

Isn't life great when it's simple?

New lines!

I thought it would be appropriate to start a new blog with a post about new lines. We've been trying to get a label in ASP.Net's Gridview to display multilines for text that a user has entered in a textbox. Basically, the user would post a message in a textbox, and the page would refresh to show the message. For some reason, new lines weren't being displayed properly. It might be just me, but I drove myself mental trying to find a solution for this online, and while string.Replace(System.Environment.NewLine, "
") worked well for hardcoded new lines, new lines which were being entered by the user just weren't rendering right.

So after much tinkering involving displaying the ascii values of all non-alphabetic and numeric characters, I found that when a user hits Enter in a text box, it's stored as ascii value (10). System.Environment.NewLine for Windows systems is (13)(10) . And so this ugly line was born:

text = text.Replace(((char)10).ToString(), (((char)13).ToString()) + (((char)10).ToString()));

Surely someone can come up with a better way than that! Please enlighten me if you do, and I hope this helps someone else who has this problem.