在ASPX中不使用声明性SqlDataSource时如何命名事件处理程序?

时间:2019-01-07 01:34:58

标签: asp.net gridview 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();
    }

0 个答案:

没有答案