[英]How to search with radio Button in c#
我正在尝试在选中DateDePublication时使用 RadioButton 过滤此表,并且搜索文本的值等于例如 2000 表应该返回DateDePublication等于 2000 的所有书籍
这是搜索按钮代码:
private void RechBtn_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = repository.GetAllLivres(rechtext.Text);
}
和搜索方法代码以返回所有书籍:
public List<Livre> FilterDateDePublication(string date)
{
using (var connection = factory.CreateConnection())
{
var livres = new List<Livre>();
connection.ConnectionString = connectionString;
connection.Open();
var command = factory.CreateCommand();
command.Connection = connection;
command.CommandText = "select * from livre where date_publication like '%" + date + "%'";
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Livre l = new Livre();
l.Isbn = reader["isbn"].ToString();
l.Titre = reader["titre"].ToString();
l.DatePublication = DateTime.Parse(reader["date_publication"].ToString());
l.NombrePage = Int32.Parse(reader["nombre_page"].ToString());
l.Couverture = reader["couverture"].ToString();
l.Prix = Double.Parse(reader["nombre_page"].ToString());
l.QuantiteDisponible = Int32.Parse(reader["quantite_disponible"].ToString());
}
}
return livres;
}
您的 function GetAllLivres 只是查找标题中带有特定字符串的书籍。
command.CommandText = "select * from livre where titre like '%" + mc + "%'";
您应该将其更改为在发布日期进行搜索。 可以说那应该是什么样子,因为我们不知道你的数据库方案。
顺便说一下,不要那样构建 SQL,这是一个巨大的安全漏洞。 使用参数化查询
我知道当其中一个被选中时我有 4 个单选按钮搜索 function 应该通过每个单选按钮查找。
好吧,又一次没有看到用户界面,这很难说,但我猜你有这样的东西
|-search by: --------| <<< group box
| ( ) Author | << radio buttons
| ( ) title |
| (*) Year |
----------------------
Search for :_________________: <<== text box
[Start Search] <<== button
希望如此。
所以这样做
if(radioYear.Checked){
FilterDateDePublication(searchText.Text);
}
else if(radioAuthor.Checked)
.......
请注意,用户输入的日期可能与数据库中日期的格式不匹配,在这种情况下,您需要进行一些修改
但是,我会重构您的代码,您肯定已经注意到 90% 的 FilterDateDePublication 与标题相同。
你应该做
public List<Livre> ReadBooks(string query)
{
using (var connection = factory.CreateConnection())
{
var livres = new List<Livre>();
connection.ConnectionString = connectionString;
connection.Open();
var command = factory.CreateCommand();
command.Connection = connection;
command.CommandText = query;
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Livre l = new Livre();
l.Isbn = reader["isbn"].ToString();
l.Titre = reader["titre"].ToString();
l.DatePublication = DateTime.Parse(reader["date_publication"].ToString());
l.NombrePage = Int32.Parse(reader["nombre_page"].ToString());
l.Couverture = reader["couverture"].ToString();
l.Prix = Double.Parse(reader["nombre_page"].ToString());
l.QuantiteDisponible = Int32.Parse(reader["quantite_disponible"].ToString());
}
}
return livres;
}
然后有
List<Livre> GetByDate(string date){
return GetBooks("select * from livre where date_publication like '%" + date + "%'";
}
更好的方法是使用 sql 参数。 我稍后会更新这个答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.