简体   繁体   English

C#字符串串联

[英]C# String Concatenation

Help me with this Problem in C#, im trying to refine the search of my gridview, this is my code, i want to the user to be able to search values with this format on textbox. 帮助我解决C#中的这个问题,我正在尝试优化我的gridview的搜索,这是我的代码,我希望用户能够在文本框中使用此格式搜索值。 (name, description) ex. (名称,说明) Food, Ice Cream, then it will filter all the food with description of ice cream. 食物,冰淇淋,然后它将过滤所有带有冰淇淋描述的食物。 Thanks. 谢谢。

((DataTable) gridTestCodes.DataSource).DefaultView.RowFilter = 
        string.Concat("name like '%{0}% + description + '%{0}%'", 
                      txtSearch.Text.Trim().Replace("'", "''"));

You're using concat in place of format . 您正在使用concat代替format Also, your query is wrong. 另外,您的查询是错误的。 You're using + instead of AND , there's a single quote missing after first '%{0}% , and description + '%{0}%' doesn't make sense. 您使用的是+而不是AND ,在第一个'%{0}%之后缺少单引号,而description + '%{0}%'则没有意义。 Try this: 尝试这个:

((DataTable)gridTestCodes.DataSource).DefaultView.RowFilter = 
    string.Format("name like '%{0}%' AND description like '%{0}%'", 
                  txtSearch.Text.Trim().Replace("'", "''"));

Or try just querying on name first and then adding in description once this works (also should the .Replace be removing the quotes all together?): 或者尝试仅先查询名称,然后在.Replace下添加描述( .Replace是否也应一起删除引号?):

((DataTable)gridTestCodes.DataSource).DefaultView.RowFilter = 
         string.Format("name like '%{0}%'", txtSearch.Text.Trim().Replace("'", string.empty));

EDIT: 编辑:

If you want to enter name then description seperated by comma try: 如果要输入名称,请用逗号分隔描述,请尝试:

var name = txtSearch.Text.Split(',')[0].Trim().Replace("'", string.empty);
var description = txtSearch.Text.Split(',')[1].Trim().Replace("'", string.empty);

((DataTable) gridTestCodes.DataSource).DefaultView.RowFilter = 
        string.Format("name like '%{0}%' AND description like '%{1}%'", name, description);

Note that the above code will throw an exception if the input string does not contain a comma. 请注意,如果输入字符串包含逗号,则上述代码将引发异常。 So you may want to add a check for that. 因此,您可能要为此添加一张支票。

Looks like you need to use string.Format instead. 看起来您需要使用string.Format代替。 string.Concat just concatenate your strings, it doesn't format them. string.Concat只是连接您的字符串,不会格式化它们。

And your expression syntax doesn't seems right. 而且您的表达式语法似乎不正确。 You need one more single quote after your first {0} and you need to use AND or OR between your criterias. 您需要在第一个{0}加上一个单引号,并且需要在两个条件之间使用ANDOR

string.Format("name like '%{0}%' AND description like '%{0}%'", 
               txtSearch.Text.Trim().Replace("'", "''"));

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

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