本文介绍了如何将变量传递给 SqlDataSource 的 SelectCommand?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将变量从后面的代码传递给 SqlDataSource 的 SelectCommand?
I want to pass variable from the code behind to the SelectCommand of a SqlDataSource?
我不想使用内置参数类型(如 ControlParameter、QueryStringParameter 等)
I don't want to use built-in parameter types (like ControlParameter, QueryStringParameter, etc)
我需要传递一个变量,但下面的例子不起作用:
I need to pass a variable, but the following example does not work:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:itematConnectionString %>" SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC" >
<SelectParameters>
<asp:Parameter DefaultValue="<%= userId %>" Name="userId" DbType="Guid" />
</SelectParameters>
</asp:SqlDataSource>
推荐答案
试试这个,移除 SelectCommand 属性和 SelectParameters:
Try this instead, remove the SelectCommand property and SelectParameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">
然后在后面的代码中这样做:
Then in the code behind do this:
SqlDataSource1.SelectParameters.Add("userId", userId.ToString());
SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"
虽然这对我有用,但以下代码也适用:
While this worked for me, the following code also works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>
SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());
这篇关于如何将变量传递给 SqlDataSource 的 SelectCommand?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!