错误转换数据类型

时间:2012-05-22 16:26:27

标签: c# asp.net vb.net

我从网址获取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>

我硬编码时代码运行正常 任何想法如何解决这个错误谢谢

1 个答案:

答案 0 :(得分: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>
相关问题