Reputation: 75
does anybody know how to make a string in c# get the text of a certain (unselected) line of a listbox? I've tried (this has itemselected):
string text = listBox1.SelectedItem.ToString();
string[] stringy = text.Split(' ');
MessageBox.Show(stringy[1]);
But that requires an item to be selected. If it was possible, this is what i'm trying to do:
string text = listBox1.GetLine.ThatContainsText("stuff stuff stuff");
string[] stringy = text.Split(' ');
MessageBox.Show(string[1]);
If somebody could help, that would be great. If you need me to provide anything else, I can.
Upvotes: 3
Views: 215
Reputation: 1215
Here's a simple solution that works if you're trying to get an exact match.
var text = listBox1.Items.FindByText("stuff stuff stuff");
Otherwise you'll have to use
var text = (from x in listBox1.Items.Cast<string>()
where x.Contains("stuff stuff stuff")
select x).FirstOrDefault();
Then just verify that 'text' isn't null
if (text != null)
{
string[] stringy = text.ToString().Split(' ');
MessageBox.Show(stringy[1]);
}
Upvotes: 0
Reputation: 4403
String text = (String)listBox.Items.Cast<string>()
.FirstOrDefault(i => ((String)i).Contains("stuff stuff stuff") && !i.Equals(listBox.SelectedItem));
Sorry for non-formated response, I'm writting this from my phone.
Upvotes: 0
Reputation: 22436
var text = (from x in listBox1.Items.Cast<string>()
where x.Contains("stuff stuff stuff")
select x).FirstOrDefault();
if (!string.IsNullOrEmpty(text))
{
string[] stringy = text.Split(' ');
MessageBox.Show(string[1]);
}
Upvotes: 0
Reputation: 1319
var textToSearchFor = "stuff stuff stuff";
var text = (from x in listBox1.Items.Cast<string>()
where x.Contains(textToSearchFor)
select x)
.FirstOrDefault(); //maybe even single, depending on your input
Upvotes: 1
Reputation: 6105
Do something like
String text = (String)listBox.Items
.FirstOrDefault(i => ((String)i).Contains("stuff stuff stuff"));
Upvotes: 0