2013-03-20 37 views
2

我想在列表<>中找到值,但我沒有得到整數值。這是我的代碼,我想找到列表中的值在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) 
    { 
    } 
} 

對我來說任何解決方案。因爲當我嘗試查找字符串值時,這適用於我。

回答

1
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(); 
    } 
} 

試試這個

1

我想找到列表中的值<>但我沒有得到整數值。

p.NapsaRate要麼是整數類型或浮點數,(可能是小數)將您txtnapsaserach.Text十進制值,然後它比較where子句。

decimal rate = 0; 
if(!decimal.TryParse(txtnapsaserach.Text), out rate) 
{ 
//Invalid number in textbox 
} 

this.napsaTableBindingSource.DataSource = 
     _napsatabs.Where(p =>p.NapsaRate == rate)).ToList(); 

如果p.NapsaRate是double類型或浮動,你可以解析它們相應使用Double.TryParseDouble.Parse

原因你沒有得到任何錯誤是您正在使用object.Equals方法比較十進制值與字符串。您應始終使用==進行值類型的平等比較。