June 04, 2010
Your Thought for the Day

PanelWithTextBoxes.Controls.Cast<System.Web.UI.Control>().Where(x => x.ID != null && x.ID.Contains("TextBox")).Cast<TextBox>() .Where(y => !string.IsNullOrEmpty(y.Text) && int.TryParse(y.Text, out i)).Select(y => y.Text).ToList().ForEach(z => obj.ListOfInts.Add(Convert.ToInt32(z)));

An actual, working piece of code. In "pseudo-code", what this translates into is "go get all the entry blanks which aren't empty, and have a NUMBER in them, inside this panel and store what a person entered in that blank as a number in a list."

Yes, I wrote it. Hopefully you're not horrified. Seems to work well, and replaces a multi-line function with a single line. Whee!

Posted by scott at June 04, 2010 04:32 PM

eMail this entry!
Comments

sweet.

i'd recommend changing the first Where() to checking that the control is of type TextBox, not that the name contains TextBox. or better, assign the controls that you want to collect values from an extra Attribute and query for that. that way, you're more explicitly specifying which textboxes to collect values from. also means they don't all have to be TextBoxs, some can be spinners, or a dropdownlist, or whatever. (of course then you'll have to complicate your Linq to deal with some controls that are .Text and others that are .Value and .SelectedValue, etc.)

Posted by: mrfred on June 4, 2010 07:22 PM

Yeah. I thought about using the type instead of the ID on the elevator down to the car right after I posted this. It also still makes me itch I have to convert the value to int twice, but I can't quite figure out how to get the i in the tryparse over to the final foreach.

Still, it's darned useful as it is.

Posted by: Scott on June 5, 2010 06:46 AM

build an extension that takes a string and returns a nullable, the number is translates to, or null if it's blank or a non-number. use THAT in the Linq statement.

Posted by: mrfred on June 5, 2010 09:06 PM
Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?