Finding a specific value in WindowsForms ListView via FindItemWithText, but method having some troubles with numbers

42 views Asked by At

I have a ListView named lst_Employees and have combined 2 ComboBoxes named cmb_EmployeeID and cmb_EmployeeName. When I choose someone from cmb_EmployeeName, the cmb_EmployeeID's selected index change and show me the ID of selected employee and I add them via a button to the lst_Employee ListView.

I use FindItemWithText method and I managed to block the process if selected user has already added to the ListView and show a message "Employee already in the list." Everything works fine but ID numbers have 2 or more digits and added to the list firstly, method blocks to add selected employees ID number has 1 digit, even he is not in the list.

To be clear; I have 30 employees on my combobox and all ID's between 1-30. When I add a person first whose ID is 1, there is no problem. But if I add an employee first whose ID between 10-19 such as 14, program add the employee to the list, after I want to try add my first employee whose ID is 1, method blocks the process and warns me "Employee already in the list." This situation happens between numbers 20-29 and number 2. It is same for numbers between 30-39 and number 3. As i understand, FindItemWithText searches desired area and whenever it finds first character equal to searched number, it does't check second digit and block my procces. For example; it searches "1" in the list and if it finds a "1" in the first digit of number "14",it blocks me.

Is there any way to overcome of this thing or can you suggest me another way?

private void btn_EmployeeAdd_Click(object sender, EventArgs e)
{
    if (cmb_EmployeeName.SelectedIndex > 0)
    {
        ListViewItem foundItem = null;
        if (lst_Employees.Items.Count > 0)
        {
            foundItem = lst_Employees.FindItemWithText(cmb_EmployeeID.Text, false, 0);
            if (foundItem != null)
            {
                MessageBox.Show("Employee has already in the list", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        if (foundItem == null)
        {
            string name = cmb_EmployeeName.Text.Substring(0, cmb_EmployeeName.Text.IndexOf(" - ["));

            ListViewItem lvi = new ListViewItem();
            lvi.Text = cmb_EmployeeID.Text;
            lvi.SubItems.Add(name); 
            lst_Employees.Items.Add(lvi);
            cmb_EmployeeName.SelectedIndex = 0;
        }
    }
    }
    else
    {
        MessageBox.Show("Please select an employee.");
    }
}
0

There are 0 answers