简体   繁体   English

搜索时从SQL结果中删除空格

[英]Remove Spaces from SQL Results When Searching

I have an Access database that contains fields with spaces in them. 我有一个Access数据库,其中包含带有空格的字段。 I'm trying to allow a user to search for matches but the spaces in the results are returning no information. 我正在尝试允许用户搜索匹配项,但结果中的空格未返回任何信息。

var dtCustomers = new DataTable();
var adapter = new OleDbDataAdapter("SELECT * FROM Devices WHERE [Serial Number]='" + textBox1.Text + "'", conn);
adapter.Fill(dtCustomers);
dataGridView1.DataSource = dtCustomers;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    row.Cells[0].Style.ForeColor = Color.Blue;
    row.Cells[28].Style.ForeColor = Color.Red;
}

The code above will return results from the database but if the database has a field that's entered as '1Z 4568 29z4h' then it won't be returned unless the user types it exactly like that. 上面的代码将从数据库中返回结果,但是如果数据库中输入的字段为“ 1Z 4568 29z4h”,则除非用户键入完全相同的字段,否则它将不会返回。 The results are displayed in a DataGridView. 结果显示在DataGridView中。 Is there a different query I should be using? 我应该使用其他查询吗?

You can use SQL's replace function to replace all spaces in [Serial Number] column to nothing, and use textBox1.Text.Replace(' ','') to make sure the user's input doesn't have spaces too: 您可以使用SQL的replace函数将[Serial Number]列中的所有空格都replacetextBox1.Text.Replace(' ','') ,并使用textBox1.Text.Replace(' ','')来确保用户的输入也没有空格:

var dtCustomers = new DataTable();
var adapter = new OleDbDataAdapter(@"SELECT * FROM Devices WHERE replace([Serial Number], " ", "")='" + textBox1.Text.Relpace(' ','') + "'", conn);
adapter.Fill(dtCustomers);
dataGridView1.DataSource = dtCustomers;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    row.Cells[0].Style.ForeColor = Color.Blue;
    row.Cells[28].Style.ForeColor = Color.Red;
}

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

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