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 に答える