0

我从 url 获取 id 并将其传递给 sqldatasource - selectcommand 我收到以下错误:

Conversion failed when converting the varchar value '<%=MyIdVal%>'
 to data type int.

后面的代码:

Public Partial Class Edit
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles    Me.Load
    MyIdVal = Request.QueryString("id")
End Sub

Private _myIdVal As Integer

Public Property MyIdVal() As Integer
    Get
        Return _myIdVal
    End Get
    Set(ByVal value As Integer)
        _myIdVal = value
    End Set
End Property

结束类

客户 :

 < head runat="server">
<title></title>
  </head>
  <body>
<form id="form1" runat="server">
<div>
<%=MyIdVal%>
</div>
<asp:GridView ID="GridView1" runat="server" DataSourceID="myIdDataSource">
</asp:GridView>
<asp:SqlDataSource runat="server" ID="myIdDataSource" 
    ConnectionString="<%$  ConnectionStrings:myCipConnection  %>" 
    ProviderName="<%$ ConnectionStrings:myCipConnection.ProviderName %>"
    SelectCommand="SELECT * FROM books WHERE id = '<%=MyIdVal%>'" >  

    </asp:SqlDataSource>

</form>
  </body>
  </html>

当我对其进行硬编码时,代码运行良好,知道如何解决此错误,谢谢

4

1 回答 1

2

您不能<%= %>在 select 命令中使用语法。您必须在查询中使用参数,并将参数添加到数据源的 SelectParameters 集合中,例如:

<asp:SqlDataSource runat="server" ID="myIdDataSource" 
  ConnectionString="<%$  ConnectionStrings:myCipConnection  %>" 
  ProviderName="<%$ ConnectionStrings:myCipConnection.ProviderName %>"
  SelectCommand="SELECT * FROM books WHERE id = @id">
     <SelectParameters>
         <asp:QueryStringParameter Name="id" Type="Int32" DefaultValue="1" />
     </SelectParameter>
</asp:SqlDataSource>
于 2012-05-22T16:32:58.617 回答