user2997877
user2997877

Reputation: 75

How to make a string get the text of a specific line of a listbox by checking if the line contains certain text?

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

Answers (5)

ovaltein
ovaltein

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

Ivan Peric
Ivan Peric

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

Markus
Markus

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

Mohammed Hossain
Mohammed Hossain

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

David S.
David S.

Reputation: 6105

Do something like

String text = (String)listBox.Items
    .FirstOrDefault(i => ((String)i).Contains("stuff stuff stuff"));

Upvotes: 0

Related Questions