Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 搜索多列-创建where子句_C#_Winforms_Datagridview_Textbox_Ado.net - Fatal编程技术网

C# 搜索多列-创建where子句

C# 搜索多列-创建where子句,c#,winforms,datagridview,textbox,ado.net,C#,Winforms,Datagridview,Textbox,Ado.net,朋友 如果你有时间解决我的问题,请告诉我 我的表单中有许多文本框,其中有一个按钮和一个datagridview 我使用此代码进行搜索 如果我想使用2个或更多文本框中的值执行搜索,该怎么办。如果我在“姓名”文本框中键入“r”,然后在“城市”文本框中键入“NY”,该怎么办。我想看看gridview,告诉我结果 这就是我试图找到的,但我什么也没找到 如果我只在一个文本框中搜索,则代码有效 问候 private void Button1_Click(object sender, EventArgs e)

朋友

如果你有时间解决我的问题,请告诉我 我的表单中有许多文本框,其中有一个按钮和一个datagridview 我使用此代码进行搜索

如果我想使用2个或更多文本框中的值执行搜索,该怎么办。如果我在“姓名”文本框中键入“r”,然后在“城市”文本框中键入“NY”,该怎么办。我想看看gridview,告诉我结果

这就是我试图找到的,但我什么也没找到

如果我只在一个文本框中搜索,则代码有效

问候

private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();

if (txtCIVILIDD.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where  CIVILIDD = '" + txtCIVILIDD.Text.Trim() + "'", con);
    sda.Fill(dt);
    con.Close();
}
else if (txtName_Arabic.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Name_Arabic like '%" + txtName_Arabic.Text + "%'", con);
    sda.Fill(dt);
    con.Close();
}
else if (txtusername.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where  username = '" + txtusername.Text.Trim() + "'", con);
    sda.Fill(dt);
    con.Close();
}
else if (comboBox1.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where status = '" + comboBox1.Text.Trim() + "'", con);
    sda.Fill(dt);
    con.Close();
}
else if (comboBox2.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where confirmation = '" + comboBox2.Text.Trim() + "'", con);
    sda.Fill(dt);
    con.Close();
}
else if (CBgender.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where gender like '%" + CBgender.Text + "%'", con);
    sda.Fill(dt);
    con.Close();
}
else if (CBNATIONALITY.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where NATIONALITY like '" + CBNATIONALITY.Text + "%'", con);
    sda.Fill(dt);
    con.Close();
}
else if (comboBoxGovernorate.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Governorate = '" + comboBoxGovernorate.Text.Trim() + "'", con);
    sda.Fill(dt);
    con.Close();
}
else if (comboBoxCity.Text.Length > 0)
{
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where City = '" + comboBoxCity.Text.Trim() + "'", con);
    sda.Fill(dt);
    con.Close();
}
dataGridView1.DataSource = dt;
我试图用这段代码解决我的问题,因为我发现“从表1中选择*,其中1=1”; 它对我来说是无效的

private void Button1_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    StringBuilder sqlcommand = "SELECT * FROM tabl1 WHERE 1=1 ";
    if (!string.IsNullOrEmpty(CBgender.Text))
    {
        sqlcommand.Append(" and GENDER LIKE '%");
        sqlcommand.Append(CBgender.Text);
        sqlcommand.Append("%'");
    }
    // repeat for other textbox fields

    dataGridView1.DataSource = dt;
}

创建
StringBuilder
对象:

StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");

您可以创建一个参数化查询,该查询将具有空值的参数视为搜索中的中性参数。例如:

SELECT * FROM Product WHERE 
    (Id = @Id OR Id IS NULL) AND
    (Name LIKE '%' + @Name + '%' OR @Name IS NULL) AND
    (Price = @Price OR @Price IS NULL) 
这样,如果对任何参数传递
NULL
,则在搜索中不会考虑该参数

另外,作为补充说明,它通过使用参数来防止SQL注入

示例

下面的示例假设您有一个名为
Product
的表,其中有一列名为
Id
as
INT
Name
as
NVARCHAR(100)
Price
as
INT

然后,要加载数据,请创建以下方法:

public DataTable GetData(int? id, string name, int? price)
{
    DataTable dt = new DataTable();
    var commandText = "SELECT * FROM Products WHERE " +
        "(Id = @Id OR @Id is NULL) AND " +
        "(Name LIKE '%' + @Name + '%' OR @Name IS NULL) AND " +
        "(Price = @Price OR @Price IS NULL)";
    var connectionString = @"Data Source=.;Initial Catalog=SampleDb;Integrated Security=True";
    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(commandText, connection))
    {
        command.Parameters.Add("@Id", SqlDbType.Int).Value = 
            (object)id ?? DBNull.Value;
        command.Parameters.Add("@Name", SqlDbType.NVarChar, 100).Value = 
            (object)name ?? DBNull.Value;
        command.Parameters.Add("@Price", SqlDbType.Int).Value = 
            (object)price ?? DBNull.Value;
        using (var datAdapter = new SqlDataAdapter(command))
            datAdapter.Fill(dt);
    }
    return dt;
}
要从
TextBox
控件获取值并传递到
GetData
,可以使用以下代码:

var id = int.TryParse(idTextBox.Text, out var tempId) ? tempId : default(int?);
var name = string.IsNullOrEmpty(nameTextBox.Text)?null:nameTextBox.Text;
var price = int.TryParse(priceTextBox.Text, out var priceId) ? priceId : default(int?);
然后,要获取数据:

var data = GetData(id, name, price);

这里有两种可能的方法。第一个使用@WelcomeOverflows的建议,即使用
DataTable的
RowFilter
属性。这样做的好处是,您只需执行一个数据库查询,并且过滤由客户端处理。但是,不可能轻松地保护
RowFilter
不受SQL注入的影响(但是,尽管您仍然可能破坏筛选意图,但对断开连接的数据源造成的损害是有限的)。此外,如果数据集非常庞大,则可能不希望立即收回整个数据集并将其保留在内存中

// call upon startup to get all the data one time
private void GetData()
{
    DataTable dataSource = new DataTable();
    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
    {
        connection.Open();
        SqlCommand selectCommand = new SqlCommand("SELECT * FROM tabl1", connection);
        SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
        adapter.Fill(dataSource);
        dataGridView1.DataSource = dataSource;
    }
}

// create a filter for the given field in the database and our control
private string CreateFilter(string fieldName, Control userInputControl, bool exactMatch)
{
    string searchValue = null;
    if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
    if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
    if (String.IsNullOrWhiteSpace(searchValue)) return null;
    if (exactMatch)
        return String.Format("{0}='{1}'", fieldName, searchValue);
    return String.Format("{0} LIKE '%{1}%'", fieldName, searchValue);
}

// set the filter on our data grid view
private void button1_Click(object sender, EventArgs e)
{            
    var filterConditions = new[] {
        CreateFilter("Name_Arabic", txtName_Arabic, false),
        CreateFilter("gender", CBgender, false),
        CreateFilter("CIVILIDD", txtCIVILIDD, true),
        CreateFilter("NATIONALITY", cbNationality, false)
        // etc.
    };

    var dataSource = (DataTable)dataGridView1.DataSource;
    if (!filterConditions.Any(a => a != null))
    {
        dataSource.DefaultView.RowFilter = null;
        return;
    }

    dataSource.DefaultView.RowFilter = filterConditions
        .Where(a => a != null)
        .Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2));
}
第二种方法是在数据库查询中直接过滤,使用SQL参数避免SQL注入

private string CreateSqlFilter(string fieldName, Control userInputControl, SqlCommand command, bool exactMatch)
{
    string searchValue = null;
    if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
    if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
    if (String.IsNullOrWhiteSpace(searchValue)) return null;

    if (exactMatch)
    {
        command.Parameters.Add(new SqlParameter("@" + fieldName, searchValue));
        return fieldName + " = @" + fieldName;
    }
    else
    {
        command.Parameters.Add(new SqlParameter("@" + fieldName, "%" + searchValue + "%"));
        return fieldName + " LIKE @" + fieldName;
    }
}

private void button2_Click(object sender, EventArgs e)
{
    SqlCommand selectCommand = new SqlCommand();

    var filterConditions = new[] {
        CreateSqlFilter("Name_Arabic", txtName_Arabic, selectCommand, false),
        CreateSqlFilter("gender", CBgender, selectCommand, false),
        CreateSqlFilter("CIVILIDD", txtCIVILIDD, selectCommand, true),
        CreateSqlFilter("NATIONALITY", cbNationality, selectCommand, false)
        // etc.
    };

    string filterCondition = filterConditions.Any(a => a != null) ? filterConditions.Where(a => a != null).Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2)) : (string)null;

    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
    {
        selectCommand.Connection = connection;
        selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl1" : "SELECT * FROM tabl1 WHERE " + filterCondition;
        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
        DataTable dataSource = new DataTable();
        adapter.Fill(dataSource);
        dataGridView1.DataSource = dataSource;
    }
}

您应该学习如何使用SQL参数——将数据粘合到字符串中进行查询在很长一段时间内都不是正确的方法。然后,不要重建数据源,只需使用DataView或RowFilter即可。@WelcomeOverflow当我搜索一个TextBox时,代码正在与我一起工作。当我测试它时(它返回null)@steve16351如果我想添加更多的2个筛选器,我应该怎么做?示例已经存在,并且有四个条件,可以扩展,你的意思是什么?@steve16351你的意思是我将使用的任何文本框都可以工作??是的,以与示例中其他文本框相同的方式添加到
filterConditions
数组中的任何组合框或文本框都将用于构建过滤器。