Search code examples
c#bindingsource

Find a value in List<>


i have a problem when i want to find value in List<> but i am not getting the integer value. Here is my code from that i want to find the value in the List .

private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
    try
    {
       //decimal find = decimal.Parse(txtnapsaserach.Text);

       if (decimal.Parse(txtnapsaserach.Text) > 0)
       {
       List<NapsaTable> _napsatabs = this.napsaTableBindingSource.List as List<NapsaTable>;
       this.napsaTableBindingSource.DataSource = 
        _napsatabs.Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text)).ToList();

       }
    }
    catch (Exception Ex)
    {
    }
}

Is any solution for me . Because this works for me when i try to find string value.

Thanks in advance.


Solution

  • You are comparing string object (text of txtnapsasearch) with float object (value of NapsaRate property) here:

    Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text))
    

    Which of course returns false (because objects have different types). Parse text to float instead and use float to filter out napsatabs list:

    private void txtnapsaserach_TextChanged(object sender, EventArgs e)
    {
         float value;
         if (!float.TryParse(txtnapsaserach.Text, out value))
             return; // return if text cannot be parsed as float number
    
         if (value > 0)
         {
            var napsatabs = napsaTableBindingSource.List as List<NapsaTable>;
            napsaTableBindingSource.DataSource = 
                napsatabs.Where(p =>p.NapsaRate == value).ToList();
         }
    }
    

    BTW be careful with usage of Equals. Here is how Equals implemented for float (and other types)

    public override bool Equals(object obj)
    {
        if (!(obj is float))
        {
            return false; // your case if obj is string
        }
        float f = (float) obj;
        return ((f == this) || (IsNaN(f) && IsNaN(this)));
    }
    

    As you can see, you can pass any object here. But comparison will occur only if passed object also float.