Reputation: 9
Hello sorry if the answer for this is already out there somewhere but I did not find it, or did not understand it. What I have to do is I have a list box in visual studio (C#) and in this list box are some options to click on.
PinturaV $100
PinturaA $105
PinturaE $115
Lijas_Ag $112
Solvente $101
If I select a line for example PinturaA $105 from the list box in a text box that I have it should show only 105. Then if I select for example Lijas_Ag $112, the text box should show...
105
112
And so on until I press the total button and it would give me the total. My problem is having just the numbers appear on the text box. I coded so that the program can read the line selected and tell me where the space is located but I don't know if this was even needed to be able to get the number into the text box. I have no Idea how to do this. Any help would be much appreciated. I left some pics in case that helps.
Thank You
Upvotes: 0
Views: 250
Reputation: 52240
The other answers are OK and will probably work. But just so you know, the typical way to handle this sort of thing is to put the data you want in the ListItems' Value
property and the text in the Text
property, like this:
private void PopulateListBox1()
{
listBox1.Add(new ListItem("100","PinturaV $100"));
listBox1.Add(new ListItem("105","PinturaA $105"));
listBox1.Add(new ListItem("115","PinturaE $115"));
listBox1.Add(new ListItem("112","Lijas_Ag $112"));
listBox1.Add(new ListItem("101","Solvente $101"));
}
And then get the Value
instead of Text
, like this:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listBox1.SelectedValue;
}
As you can see this is far, far simpler than parsing the string returned by ListItem.Text
.
Upvotes: 0
Reputation: 4066
You should use Regex
to get your desired output. You need to apply Regex
in your ListBox
event
. Please check below for Regex
& C#
example.
Regex:
\d+
Above Regex
will give you all digit
from your string
CODE C#:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Your others code & logic
//string data = "PinturaV $100";
string data = listBox1.Text;
textBox1.Text = Regex.Match(data, @"\d+").Value;
}
Upvotes: 1
Reputation: 1801
You could use Regex and just do
var item = "Solvente $101";
var val = Regex.Match(item, @"\$(\d+)").Groups[1];
Upvotes: 0
Reputation: 3667
You can do this easily with a regex:
var oldtext = "Solvente $101";
var newtest = Regex.Match(oldText, "\\d+$").Groups[0].Value;
The variable newtext
will contain the digits.
Upvotes: 0
Reputation: 77876
Considering the selected text is PinturaA $105
.. you can use regular expression (or) string library method to get only the numbers like
string str = "PinturaA $105";
string val = (str.IndexOf("$") > 0)
? str.Substring(str.IndexOf("$"), str.Length - str.IndexOf("$"))
: string.Empty;
Upvotes: 0