asp.net - 在 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();
}
解决方案
推荐阅读
- r - 如果字符串在 R 中包含 x do y
- python - Detectron 2自定义权重文件未检测到物体
- aws-lambda - AWS lambda 返回错误的输出
- sql - 未分区表的分区视图的性能
- python - Python Selenium 动态链接错误信息
- c# - 使用 json 补丁找不到路径段指定的目标位置
- c - 从文件中读取邻接矩阵 - 竞争性编程
- widget - 在 GridLayout 列中对齐小部件并使所有小部件在 kivy 中的宽度相同大小时出现问题,有没有办法解决这个问题?
- python - 如何使用 shamirs 秘密共享存储和拆分共享 aes 密钥和 iv?
- sql - 如何在 django 中单独获取特定文件?