Compare input to list

Total Post:154

Points:1086
C# 
C#
 1124  View(s)
Ratings:
Rate this:

Is it possible to compare the input text in a textbox in a windows form to the items in a list and then save it if it doesn't exist there. 

public Form1()
{
    InitializeComponent();
    if (txtId.Text == Id.myList)
    {
        myList.Add(txtId.Text);
    }
    else (){
        MessageBox.Show("Id already exists");
    }
}
  1. Post:412

    Points:2888
    Re: Compare input to list

    Hi Manoj,

    You can loop trough all the items in the list and create a bool variable to check whether you have found the value in the list.

    bool _Found = false;
    foreach (string a in list)
    {
        if (a == textBox1.Text)
        {
            _Found = true;
            break;
        }
        else
            _Found = false;
    }
    if (_Found) { }
    else { list.Add(textBox1.Text) }
    Or use List(T).Contains Method
    if (list.Contains(textBox1.Text)) { }

      Modified On Apr-03-2018 11:57:33 PM

Answer