如何将此示例 aspx 代码移至 aspx.cs(以实现代码隐藏)?
我有一个下拉列表,其中填充了来自 SQL 数据库的数据。这就是我在 aspx 文件中可能有的内容。如何将代码从 aspx 文件移动(尽可能多)到 aspx.cs 文件以实现代码隐藏技术? 我的意思是至少 SELECT 部分。 谢谢。
<asp:DropDownList ID="DropDownList1" ... runat="server"/>
...
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Pubs %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = @state">
<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
I have a dropdownlist which is populated with data from an SQL db. This is what I might have in the aspx file. How do I move (as much as possible) the code from the aspx file to the aspx.cs file to implement the code behind technique?
I mean at least the SELECT portion.
Thanks.
<asp:DropDownList ID="DropDownList1" ... runat="server"/>
...
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Pubs %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = @state">
<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您正在将网格与数据源
SqlDataSource1
绑定,那么您可以在代码隐藏中捕获SelectedIndexChanged
事件并获取数据来绑定网格,如下所示:ASPX 文件:
C#(代码隐藏):
suppose you are binding a grid with data source
SqlDataSource1
then you can catchSelectedIndexChanged
event in codebehind and get data to bind the grid like this:ASPX file:
C# (codebehind):
SelectCommand
是您正在使用的数据源对象的属性。这些可以根据需要应用在后面的代码中,但您可能希望在重写的 Init 页面函数中执行此操作,因为这可能会在 ASP.NET 页面生命周期的早期使用。例如,虽然我不确定具体在哪里。您还必须确保在后面的代码中正确使用 @state 参数,这也可以作为属性进行访问 (
dsMySource.SelectParameters
)。The
SelectCommand
is a property of the datasource object you are using. These can be applied in the code behind as needed, but you may want to do it in an overridden Init page function as this might be used quite early on in the asp.net page life cycle. for eg, although I'm not sure exactly where.You are also going to have to make sure the @state parameter is used correctly in the code behind as well, this can be accessed also as a property (
dsMySource.SelectParameters
).