Lil' question about parsing
Hi, everyone, I hope to find some answer to my question here. I hope this is the right section... ^^
See, I have a ComboBox, which items are, for example, "2 Years", "5 Years", and "10 Years." In my code, there is one part where one of my buttons has to take note of these values, but int-shaped, if you know what I mean. I've tried Parse and TryParse, but of course they did not work; I think I get zero all the times. So my question is: do I have to...
if (ComboBox.text="2 Years")
return 2;
Or there's a function that could replace this?
Thanks in advance!
Re: Lil' question about parsing
Quote:
Or there's a function that could replace this?
Why not just write one ?
e.g.
Code:
public static int GetYears(string x)
{
for (int index = 0; index < x.Length; ++index)
{
if (!char.IsDigit(x[index]))
{
string years = x.Substring(0, index);
if (string.IsNullOrEmpty(years))
{
throw new ApplicationException("No digits at start of year string");
}
return int.Parse(years);
}
}
return int.Parse(x);
}
You could also use regex-s or use a custom class to populate your combo box e.g.
Code:
class YearComboBoxItem
{
public int Years { get; set; }
public string ToString()
{
return string.Format("{0} years", this.Years);
}
}
myComboBoxItems.Add(new YearComboBoxItem() { Years = 2 });
myComboBoxItems.Add(new YearComboBoxItem() { Years = 4 });
myComboBoxItems.Add(new YearComboBoxItem() { Years = 8 });
YearComboBoxItem selecteDItem = myComboBoxItems.SelectedItem as YearComboBoxItem;
if (selectedItem != null)
{
int years = selectedItem.Years;
}
I personally prefer the last approach because it means you can change the format of the combo box item (e.g. with respect to language) without changing any of the code.
Darwen.
Re: Lil' question about parsing
Seems like there's no function to simplify my code... thanks, I'll go with one of these options, then.
Re: Lil' question about parsing
I would go one step further and simply create your own class for this. The ComboBox will call ToString to display the items, so your class can just override that method for display purposes, and expose an int property for backend data collection:
Code:
class Whatever
{
public Whatever( int years )
{
Years = years;
}
public int Years { get; private set; }
public override string ToString()
{
return String.Format( "{0} years", Years );
}
}
Now just add instances of the "Whatever" class to the ComboBox:
Code:
comboBox.Items.Add( new Whatever( 2 ) );
comboBox.Items.Add( new Whatever( 5 ) );
// ...
// and to get them back...
var item = (Whatever)comboBox.SelectedItem;
int years = item.Years; // no parsing required