如何将字符串变量分配给SelectCommand

时间:2012-01-16 20:32:21

标签: c# asp.net .net connection-string sqldatasource

我在两个字符串变量中有两个select语句(Str1Str2)。我还有一个条件,选择适当的select语句并将其分配给另一个字符串(res)。

这是要在我的网页上分配给SelectCommand控件的SqlDataSource属性的select语句。

代码是:

int id =1;
string Str1 = "Select * from table";
string Str2 = "Select * from table where id = "+id;
string res;
if(id == 0)
{
  res=Str2;
}else
{
  res=Str1;
}

我的标记看起来像:

<asp:gridview.....></aspgridview>
<asp:SqlDataSource ID="ds1" runat="server"
  ConnectionStrings="<%ConnectionStrings.ConnStr%>"
  SelectCommand="<%# res%>">
</asp:SqlDataSource>

如何从我的代码隐藏或内联C#代码中将我的字符串变量res分配给SqlDataSource SelectCommand属性?

3 个答案:

答案 0 :(得分:3)

您可以通过在if / else块之后添加以下语句来设置代码隐藏中的SelectCommand属性:

ds1.SelectCommand = res;

然后您可以从标记代码中删除表达式:

<asp:SqlDataSource ID="ds1" runat="server"
  ConnectionStrings="<%ConnectionStrings.ConnStr%>" />

答案 1 :(得分:1)

你应该像在msnd上的Using Parameters with the SqlDataSource Control文章一样使用它。

如果您只是追加这样的字符串,那么您将会遇到SQL注入漏洞。

答案 2 :(得分:0)

以编程方式为SelectCommand编译SqlDataSource

ds1.SelectCommand = res;

res是您的命令文本。

相关问题