C# 转换数据类型时出错
我正在从url获取id并将其传递给sqldatasource-selectcommand,我收到以下错误:C# 转换数据类型时出错,c#,asp.net,vb.net,C#,Asp.net,Vb.net,我正在从url获取id并将其传递给sqldatasource-selectcommand,我收到以下错误: Conversion failed when converting the varchar value '<%=MyIdVal%>' to data type int. 末级 客户: < head runat="server"> <title></title> </head> <body> <for
Conversion failed when converting the varchar value '<%=MyIdVal%>'
to data type int.
末级
客户:
< 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>
当我硬编码时,代码运行良好
如果您知道如何修复此错误,请多谢您不能在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>
如果你告诉我如何设置它,我真的很感激+1:哦,布莱恩,我没有看到编辑,为什么我的答案是抄袭猫:)@MinaGabriel correction,你不需要编程设置它;它会自动为您引入查询字符串值。
<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>