首页 > 解决方案 > 在 ASPX 中不使用声明性 SqlDataSource 时如何命名事件处理程序?

问题描述

我想从在 aspx 页面中使用声明性 SqlDataSource 控件转移到代码后面。如果没有数据源 ID,我如何为 Selected、Selecting、PreRender 等事件编写处理程序?如果有更好的方法来做到这一点,请告诉我。

//With a datasource named MyDS, I can do this in ASPX:
    <asp:GridView ID="gvReport" runat="server" DataSourceID="ID="MyDS"> </asp:GridView>

    <asp:SqlDataSource ID="MyDS" runat="server" ConnectionString="<%$ ConnectionStrings:csM7DB02 %>"
        SelectCommand="SELECT Top(50) M7Sd.StudyID FROM StudyData M7Sd"
        OnSelecting="MyDS_Selecting" OnSelected="MyDS_Selected">
    </asp:SqlDataSource>

//And this in code behind:
    protected void MyDS_Selecting(object sender, SqlDataSourceSelectingEventArgs e) {
            e.Command.CommandTimeout = 180;     //Change timeout for slow queries
        }

//BUT, if I don't use a datasource control in ASPX, I won't have a datasource ID to name the handlers.
//So how can I code handler for the datasource events using the following approach?

//ASPX:
    <asp:GridView ID="gvReport" runat="server"> </asp:GridView>  //NOT USING A DATASOURCE

//CODE BEHIND:
    protected void Page_Load(object sender, EventArgs e) {
        if ( ! IsPostBack )  {
            GetData();
        }
    }

    private void GetData()  {
        DataTable table = new DataTable();
        using (SqlConnection conn = new SqlConnection(constr))  {
            string sql = "SELECT Top(50) M7Sd.StudyID FROM StudyData M7Sd";
             using (SqlCommand cmd = new SqlCommand(sql, conn))  {
                using (SqlDataAdapter ad = new SqlDataAdapter(cmd)) {
                    ad.Fill(table);
                }
            }
        }
        gvReport.DataSource = table;
        gvReport.DataBind();
    }

标签: asp.netgridviewsqldatasource

解决方案


推荐阅读