【发布时间】:2016-03-21 17:02:53
【问题描述】:
我有一个代码隐藏方法,它使用 SqlDataSource 对象从数据库中检索数据,然后用作我的网格视图的数据源来显示记录。我需要有条件地向我的 SelectCommand 查询的 WHERE 子句添加另一个条件,并且需要通过参数将数据传递给查询。我该怎么做?
SqlDataSource sds = new SqlDataSource();
sds.SelectCommand = "Select CustomerName, LoanNumber, LoanDate FROM Loan WHERE IsActive = 1 ";
if (filterRecord != "All") { // DDL filter on page, all records by default
sds.SelectCommand += "AND LoanType = ??"; //this is where I need to parameterize my query
}
我想像
if (filterRecord != "All") {
sds.SelectCommand += "AND LoanType = @LoanType";
sds.SelectParameters.Add("@LoanType", "Mortgage");
}
但这似乎不起作用。
【问题讨论】:
-
But that does not appear to work.什么不起作用?有例外吗? -
它说“必须声明标量变量“@LoanType”。
-
您使用的是
LoanType = ??还是LoanType = @LoanType? -
我正在使用 LoanType = @LoanType。第一个例子只是暗示我不知道该放什么
-
不应该是
sds.SelectParameters.AddWithValue吗?