views:

130

answers:

2

How do I check if a listView contains a DateTime or String?

I've tried

if (!listView1.Items.Contains(SetAlarm.Value))

But it cannot convert System.DateTime to System.Windows.Forms.ListViewItem.

A: 

listView1.Items.Contains(new ListItem(DateTime.Now)) will not work. Contains only works if we are passing an Item actually in ListView.Items collections. I think you will have to use a for loop :(

foreach (ListViewItem s in listView1.Items)
{
    if (s.Text != SetAlarm.Value.ToString()) continue;
    MsgBox.Show("Found: " + SetAlarm.Value.ToString());
    return;
}
TheVillageIdiot
This method works just fine. Thanks!
Kevin
A: 
    bool isMatch = false;

    int matchIndex = -1;

    DateTime resultDate = = new DateTime();

    foreach(ListViewItem lvItem in listView1.Items)
    {
        if(DateTime.TryParse(lvItem.Text, out resultDate ))
        {
           isMatch = true;
           matchIndex = lvItem.Index;
           break;
        }
    }

    if(isMatch) Console.WriteLine("match at index : " + matchIndex.ToString() + " = " + resultDate.ToString());
BillW