如何将变量传递给SqlDataSource的SelectCommand? [英] How to pass a variable to the SelectCommand of a SqlDataSource?

查看:185
本文介绍了如何将变量传递给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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆