一种方法是使用NULL
宗教的值,并将其转换%
为 SQL Server 中的LIKE
比较。
另外 - 我总是将 UI 代码(事件处理程序等)与实际的数据库访问代码分开 - 所以在一个单独的DataAccess
类中做这样的事情(而不是将它直接粘贴到页面代码隐藏中):
public List<RuserResults> GetRuserResults(int minAge, int maxAge, string religion)
{
string selectStmt = "SELECT Age, City, State, Caste, IncomeMin, IncomeMax FROM Ruser " +
"WHERE Age BETWEEN @MinAge AND @MaxAge " +
"AND Religion LIKE @religion";
// set up your connection and command objects
using(SqlConnection conn = new SqlConnection("--your-connection-string-here--"))
using(SqlCommand cmd = new SqlCommand(selectStmt, conn))
{
// define the parameters
cmd.Parameters.Add("@MinAge", SqlDbType.Int).Value = minAge;
cmd.Parameters.Add("@MaxAge", SqlDbType.Int).Value = maxAge;
cmd.Parameters.Add("@Religion", SqlDbType.VarChar, 100);
// if you passed a value for the method parameter - use that value
if(!string.IsNullOrEmpty(religion))
{
cmd.Parameters["@Religion"].Value = religion + "%";
}
else // if no value was passed - just search for all religions
{
cmd.Parameters["@Religion"].Value = "%";
}
List<RuserResult> results = new List<RuserResult>();
// open connection, run query, close connection
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// read the values, convert to a "RuserResults", and pass it back
results.Add(ConvertReaderToRuserResult(reader));
}
}
conn.Close();
// return the results
return results;
}
}
然后从您的 ASP.NET 页面中,您可以调用它
int minAge = Convert.ToInt32(drplistagemin.SelectedItem);
int maxAge = Convert.ToInt32(drplistagemax.SelectedItem);
string religion = drplistreligion.SelectedItem;
List<RuserResult> results = GetRuserResults(minAge, maxAge, religion);
// do something with the results returned here....