Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

    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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top