![](/img/trans.png)
[英]Search data from SQL Database using multiple textbox and a Search Button
[英]Search SQL Server database with multiple text box values with search button
如果我在id
文本字段中輸入值,則只能從數據庫取回條目,但是當我在其他文本字段中輸入任何內容時,如果確定它們在其中,則不會返回任何結果。
這是我的代碼:
protected void SearchButton_Click(object sender, EventArgs e)
{
String commandString = "SELECT * FROM [Swim] WHERE (([First Name] LIKE '%' + @First_Name + '%') AND ([Last Name] LIKE '%' + @Last_Name + '%') AND ([Phone] LIKE '%' + @Phone + '%') AND ([id] = @id))";
//SELECT * FROM [Swim] WHERE ([Phone] LIKE '%' + @Phone + '%')
SqlCommand command = new SqlCommand(commandString, conn);
command.Parameters.Add("@First_Name", SqlDbType.NVarChar).Value = FirstNameTextBox.Text;
command.Parameters.Add("@Last_Name", SqlDbType.NVarChar).Value = LastNameTextBox.Text;
command.Parameters.Add("@id", SqlDbType.NVarChar).Value = IdTextBox.Text;
command.Parameters.Add("@phone", SqlDbType.NVarChar).Value = PhoneTextBox.Text;
conn.Open();
command.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
}
有什么建議會有所幫助嗎?
認真考慮使用諸如Entity Framework之類的東西,而不是在代碼中浪費SQL文本。
我在這里猜測您想允許對一個或多個字段進行查詢。
為了滿足使用Entity Framework和使用LINQ進行查詢的要求,您可以執行以下操作:
var query = db.Swims;
// ID overrides all others, since it is unique no point adding more filters unless
// you want to not return the row if the other filters don't match?
if (IdTextBox.Text.Length > 0)
{
int id = Convert.ToInt32(IdTextBox.Text);
query = query.Where(s => s.Id == id);
}
else
{
if (FirstNameTextBox.Text.Length > 0)
{
query = query.Where(s => s.FirstName.Contains(FirstNameTextBox.Text));
}
if (LastNameTextBox.Text.Length > 0)
{
query = query.Where(s => s.LastName.Contains(LastNameTextBox.Text));
}
if (PhoneTextBox.Text.Length > 0)
{
query = query.Where(s => s.Phone.Contains(PhoneTextBox.Text));
}
}
GridView1.DataSource = query.ToList();
上面的代碼可以毫無問題地處理所有8種左右的查詢組合。
我在這里做了一些未在您的問題中明確提出的假設,請讓我知道是否有錯,我將相應地更新答案。
試試這個:
SELECT * FROM Swim WHERE(First_Name LIKE'%'+ @First_Name +'%'AND Last_Name LIKE'%'+ @Last_Name +'%'and Phone LIKE'%'+ @Phone +'%')OR(id = @ ID));
首先,我建議(如果可能)將其放入sql存儲過程中。 這更多的是個人喜好,因為我更多地在數據庫方面。 當我們在應用程序層和數據庫層之間編寫代碼時,如果您必須並且更容易(對我而言)在兩者之間存儲/檢索數據,那么重構存儲的proc會容易得多。
如果您有興趣,我可以發布一個示例,說明如何使用c#和存儲的proc。
至於您的問題..不應該這樣:command.ExecuteNonQuery(); 是這樣的:command.ExecuteQuery嗎?
我使用command.ExecuteNonQuery將更新/信息發送到數據庫層,並使用command.ExecuteQuery將信息拉到應用程序層。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.