using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ICT_Assigment_3
{
public partial class search : Form
{
public search()
{
InitializeComponent();
}
DataTable dbdataset;
private void button1_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=password";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(" select BookName,Publisher,Category,Edition,Year,Location from library.add_update ;", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(dbdataset);
DV.RowFilter = string.Format("BookName LIKE '%{0}%'", search_box.Text);
dataGridView1.DataSource = DV;
}
}
}
我已经完成了搜索功能,但它只是可以按名称搜索我的数据库,如何添加其他列,如发布者,我输入名称,它也会显示与类别,位置等相同的书。任何人都可以帮助我改善这个?谢谢
答案 0 :(得分:1)
我强烈建议您使用参数化查询o动态构建它:
private DataTable FilterRecords()
{
bool where_set = false;
DataTable table = new DataTable();
string constring = "datasource=localhost;port=3306;username=root;password=password";
string commandText = "select BookName, Publisher, Category, Edition, Year,"
+ "Location from library.add_update "
+ "where "
// build your own filters
//
if (filter_by_name)
{
commandText += "name like '%" + varName + "%'";
where_set = true;
}
if (filter_by_publisher)
{
if (where_set) commandText += " and ";
commandText += "name like '%" + varName + "%'";
where_set = true;
}
using (MySqlConnection connection = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter();
adp.SelectCommand = new MySqlCommand(commandText, connection);
adp.Fill(table);
}
return table;
}
看一下,你必须修改过滤器。
在您的类中添加类似的函数,并在每次要过滤某些记录时将其分配给datagrid的bindigsource。使用一些变量告诉函数要过滤的内容,或者将过滤器作为函数参数传递并将其添加到commandText;
DataGrid.DataSource = FilterRecords();