C# 文本框为空时的默认参数
我用这个来过滤表格C# 文本框为空时的默认参数,c#,winforms,parameters,sql-server-2008-r2,C#,Winforms,Parameters,Sql Server 2008 R2,我用这个来过滤表格 using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) { myDatabaseConnection.Open(); using (SqlCommand mySqlCommand = new SqlCommand("Select * from Em
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");
}
}
}
使用(SqlConnection myDatabaseConnection=newsqlconnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
使用(SqlCommand mySqlCommand=new SqlCommand(“Select*from Employee其中EmpID>=@from和EmpID)最简单的方法是为空文本框默认@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");
}
使用(SqlCommand mySqlCommand=newsqlcommand{Connection=myDatabaseConnection})
{
mySqlCommand.CommandText=“从员工中选择*,其中”+
textBox2.Text.Trim()==“”?“EmpID>=@from”:EmpID>=@from和EmpID这个表的最后一个值是什么意思
?什么表?Employee表。我指的是EmpID的最高值。我的EmpID列是identity,这就是我为什么说最后一个值的原因。对不起。如果您的EmpID
具有整数格式的值,您可能需要检查下面给出的解决方案,它应该工作,但是请注意textBox1.text
,它应该是textBox1.text
。您需要的是,如果textBox2
为空,查询应该从textBox1
中指定的最低EmpID
中获取所有记录,获取所有
不要求我们知道EmpID的最大值
,这就是为什么您可以传入一个大数字(例如99999
)。同样的逻辑适用于textBox1
为空的情况,我们只传入尽可能小的数字(例如0
)。你可能是某种脚本编写者
?不太关心大小写敏感度?不太关心数据类型?顺便说一句文本框的默认值。文本
是字符串。空的
不是空的
。你很正确。下次发布前检查一下是明智的做法-谢谢