朋友
请您有时间解决我的问题 我的表单中有很多文本框,其中有一个按钮和一个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;
我尝试用此代码解决我的问题,我发现“ SELECT * FROM tabl1 WHERE 1 = 1”; 它向我返回null
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;
}
答案 0 :(得分:2)
这是两种可能的方法。第一个使用@WelcomeOverflows的建议,即使用RowFilter
的{{1}}属性。这样做的好处是您只需要执行一个数据库查询,并且过滤是在客户端进行的。但是,无法轻松地保护DataTable
免受SQL注入的侵害(但是尽管您仍然可以潜在地颠覆过滤意图,但是对断开连接的数据源所造成的损害是有限的)。另外,如果数据集非常庞大,则可能不希望一次撤回整个数据集并将其保存在内存中。
RowFilter
第二种方法是使用SQL参数直接在数据库查询中进行过滤,以避免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));
}
答案 1 :(得分:0)
创建StringBuilder
对象:
StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");
答案 2 :(得分:0)
您可以创建参数化查询,该查询将具有空值的参数视为搜索中性。例如:
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
为INT
,Name
为NVARCHAR(100)
和{{1} }设为Price
。
然后要加载数据,请创建以下方法:
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?);