[英]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.