ASP.NET中SqlDataSource.Select()未执行的问题排查
SqlDataSource.Select()无结果问题排查与修复
你的SqlDataSource绑定GridView时能正常填充数据,但后台手动调用Select()方法时无返回结果、OnSelecting/OnSelected事件不触发,核心原因是SelectCommand未明确配置和重复参数冲突,具体修复步骤如下:
1. 补充SelectCommand属性
GridView绑定可能通过设计器自动关联了查询逻辑,但手动调用Select()必须明确指定SelectCommand。在SqlDataSource控件中添加查询语句:
<asp:SqlDataSource ID="DataSourcePFEP" runat="server" OnSelecting="DataSourcePFEP_Selecting" OnSelected="DataSourcePFEP_Selected" ConnectionString="<%$ ConnectionStrings:DALI %>" ProviderName="Oracle.ManagedDataAccess.Client" CancelSelectOnNullParameter="false" <!-- 替换为你的实际查询语句 --> SelectCommand="SELECT Material, SupplierID, 其他字段 FROM 你的表名 WHERE PlantID = :PlantID AND ProductionLine = :ProductionLine"> <SelectParameters> <asp:SessionParameter Name="PlantID" SessionField="PlantID" /> <asp:QueryStringParameter Name="ProductionLine" QueryStringField="Line" ConvertEmptyStringToNull="true" /> <asp:SessionParameter Name="ProductionLine" SessionField="ProductionLine" /> </SelectParameters> </asp:SqlDataSource>
2. 解决重复参数冲突
你定义了两个同名的ProductionLine参数(QueryString和Session类型),手动调用Select()时控件无法确定使用哪个参数值,导致查询逻辑异常。修改方案:
- 移除重复参数,保留一个普通参数,后台动态赋值优先级
<SelectParameters> <asp:SessionParameter Name="PlantID" SessionField="PlantID" /> <asp:Parameter Name="ProductionLine" Type="String" /> </SelectParameters>
- 在
OnSelecting事件中设置参数值(优先取QueryString,不存在则用Session):
protected void DataSourcePFEP_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { string productionLine = Request.QueryString["Line"] ?? Session["ProductionLine"]?.ToString(); e.Command.Parameters["ProductionLine"].Value = productionLine; }
3. 调用Select()前验证参数有效性
确保Session和参数值存在,避免空参数导致查询无结果:
// 先验证必要参数 if (Session["PlantID"] == null) { // 处理PlantID为空的情况 return; } string productionLine = Request.QueryString["Line"] ?? Session["ProductionLine"]?.ToString(); if (string.IsNullOrEmpty(productionLine)) { // 处理ProductionLine为空的情况 return; } // 执行查询并判断结果 DataView dataView = (DataView)DataSourcePFEP.Select(new DataSourceSelectArguments()); if (dataView.Count == 0) { // 无数据的处理逻辑 return; } // 筛选目标行(注意避免SQL注入) DataRow[] targetRows = dataView.ToTable().Select($"Material = '{CommandArguments[0]}' AND SupplierID = '{CommandArguments[1]}'"); if (targetRows.Length > 0) { DataRow part = targetRows[0]; // 后续逻辑 }
4. 修复SQL注入风险
直接拼接字符串到Select()筛选条件存在SQL注入漏洞,建议改用参数化查询:
DataTable dt = dataView.ToTable(); using (var cmd = dt.DefaultView.Table.CreateCommand()) { cmd.CommandText = "SELECT * FROM WHERE Material = @Material AND SupplierID = @SupplierID"; cmd.Parameters.AddWithValue("@Material", CommandArguments[0]); cmd.Parameters.AddWithValue("@SupplierID", CommandArguments[1]); DataRow[] rows = dt.Select(cmd.CommandText); if (rows.Length > 0) { DataRow part = rows[0]; } }
内容的提问来源于stack exchange,提问作者Dinosbacsi
相关产品推荐
相关产品推荐

