简体   繁体   English

如何从文本框C#在LINQ中接受输入

[英]How to take input in LINQ from textbox C#

I have a data table dt_Customers which contains some customers information. 我有一个数据表dt_Customers ,其中包含一些客户信息。 In this data table I want to select a range of ZIP codes which the user will enter using a text box. 在此数据表中,我要选择用户将使用文本框输入的邮政编码范围。

I am using following code: 我正在使用以下代码:

IEnumerable<DataRow> enumerableDataRowCollection =
   from company in dt_Customers.AsEnumerable()
   let zip = company.Field<string>("ZIP")
   where (!string.IsNullOrEmpty(zip) && (zip[0] >= "'" + txtBox_ZIP_From.Text + "'" && zip[0] <=  "'" + txtBox_ZIP_to.Text + "'"))

   select company;

But I am getting an error 但是我遇到一个错误

Operator '>=' cannot be applied to operands of type 'char' and 'string'

The above code works fine when I hard code some value, like this: 当我对某些值进行硬编码时,上述代码可以正常工作,如下所示:

zip[0] >= '2' && zip[0] <= '6'

Zip[0] is a character, and txtBox_ZIP_From.Text is a String. Zip[0]是一个字符,而txtBox_ZIP_From.Text是一个字符串。 In the given hard-coded example you're comparing a character and a character. 在给定的硬编码示例中,您正在比较一个字符和一个字符。

IEnumerable<DataRow> enumerableDataRowCollection =
   from company in dt_Customers.AsEnumerable()
   let zip = company.Field<string>("ZIP")
   where (!string.IsNullOrEmpty(zip) && (zip >= txtBox_ZIP_From.Text && zip <=  txtBox_ZIP_to.Text))

if txtBox contient a singel char 如果txtBox包含一个单字符

var cCriterFrom = txtBox_ZIP_From.Text.Text[0];
var cCriterTo = txtBox_ZIP_to.Text.Text[0];

IEnumerable<DataRow> enumerableDataRowCollection =
   from company in dt_Customers.AsEnumerable()
   let zip = company.Field<string>("ZIP")
   where (!string.IsNullOrEmpty(zip) && (zip[0] >= cCriterFrom && zip[0] <= cCriterTo))

The problem is that zip is a string , so zip[n] is a char . 问题是zip是一个string ,所以zip[n]是一个char If you want to compare strings, try this: 如果要比较字符串,请尝试以下操作:

string.Compare(zip, txtBox_ZIP_From.Text) >= 0 &&
string.Compare(zip, txtBox_ZIP_To.Text) <= 0

However, it might be better to convert zip and the text box inputs to numbers, and compare them that way. 但是,最好将zip和文本框输入转换为数字,然后以这种方式进行比较。

Or if you just want to compare the first characters in each string, you can use this: 或者,如果您只想比较每个字符串中的前几个字符,则可以使用以下命令:

zip[0] >= txtBox_ZIP_From.Text[0] && zip[0] <=  txtBox_ZIP_to.Text[0]

Try this: 尝试这个:

IEnumerable<DataRow> enumerableDataRowCollection =
   from company in dt_Customers.AsEnumerable()
   let zip = company.Field<string>("ZIP")
   where (!string.IsNullOrEmpty(zip) && (zip.CompareTo(txtBox_ZIP_From.Text) >= 0) && (zip.CompareTo(txtBox_ZIP_to.Text) <=0))    
   select company;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM