如果textBox为空,则为默认参数
本文关键字:默认 参数 textBox 为空 如果 | 更新日期: 2023-09-27 18:27:24
我用这个来过滤表。
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select * from Employee WHERE EmpID >= @from AND EmpID <= @to", myDatabaseConnection))
{
mySqlCommand.CommandType = CommandType.Text;
mySqlCommand.Parameters.AddWithValue("@from", textBox1.Text);
mySqlCommand.Parameters.AddWithValue("@to", textBox2.Text);
{
ds = new DataSet();
adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds, "Employee");
}
}
}
例如,我在textBox1中有4001
,在texBox2中有4017
。给出了4001
、4002
、4003
。4017
例如,问题是在textBox1中为I 4001
,而在textBox2中为none,它没有给出任何结果。我将如何获得从4001
到表的最后一个值的结果?如果textBox1为空,textBox2为4017
,则假设1的值最小,则结果将为1、2、3到4017?
最简单的方法是将@from和@to的值默认为空文本框的最小值和最大值
例如。如果EmpId是整数
int minId = 0;
int maxId = 99999;
if (!string.IsNullOrEmpty(textBox1.text))
minId = int.Parse(textBox1.text);
if (!string.IsNullOrEmpty(textBox2.text))
maxId = int.Parse(textBox2.text);
mySqlCommand.Parameters.AddWithValue("@from", minId);
mySqlCommand.Parameters.AddWithValue("@to", maxId);
这样做,你总是会有一个值得比较的价值。
对于您的需求,这应该有效:
using (SqlCommand mySqlCommand = new SqlCommand {Connection = myDatabaseConnection})
{
mySqlCommand.CommandText = "Select * from Employee WHERE " +
textBox2.Text.Trim() == "" ? "EmpID >= @from" : "EmpID >= @from AND EmpID <= @to";
mySqlCommand.CommandType = CommandType.Text;
mySqlCommand.Parameters.AddWithValue("@from", textBox1.Text.Trim() != "" ? textBox1.Text : int.Parse(textBox2.Text.Trim()) - 3);
if(textBox2.Text.Trim() != "")
mySqlCommand.Parameters.AddWithValue("@to", textBox2.Text);
ds = new DataSet();
adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds, "Employee");
}