我在我的ASP代码中定义了一个SqlDataSource,我试图从我的C#代码隐藏中访问它。我收到错误消息来源未知。我该怎么办才能从代码隐藏中访问它?
C#代码 -
protected void OnEditingGridView1(object sender, GridViewEditEventArgs e)
{
GridViewRow row = GridView1.Rows[e.NewEditIndex];
int index = row.RowIndex;
string ClientKey = GridView1.DataKeys[index].Values["ClientKey"].ToString();
SqlDataSourceDebtor.SelectParameters.Clear();
SqlDataSourceDebtor.SelectParameters.Add("clientKey", ClientKey);
}
ASP代码 -
<EditItemTemplate>
<asp:DropDownList ID="ddlDebtorName" runat="server"
DataSourceID="SqlDataSourceDebtor" DataTextField="Name"
DataValueField="DebtorKey">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceDebtor" runat="server"
ConnectionString="<%$ ConnectionStrings:AuditDevConnectionString2 %>"
SelectCommand="sp_fc_vm_getDebtorList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" DefaultValue="0" Name="ClientKey"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
答案 0 :(得分:2)
SqlDataSource位于EditItemTemplate中。这意味着这个GridView,Repeater的每一行都会有一个SqlDataSource - 不管这是什么。
如果你想获得GridView中第三行的SqlDataSource,你需要这样的东西:
gv.Rows[2].FindControl("SqlDataSourceDebtor") as SqlDataSource;
编辑 - 我做了一个快速测试,这很好用:
<asp:GridView runat="server" ID="gv">
<Columns>
<asp:BoundField DataField="str" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList runat="server" DataTextField="name" DataValueField="id" DataSourceID="sqlId"></asp:DropDownList>
<asp:SqlDataSource runat="server" ID="sqlId" ConnectionString="Data Source=DevAdam;Initial Catalog=ZoomieRest;Integrated Security = true;"
SelectCommand="Select top 10 id, name from zoomiesql.subjects where userid = 7"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
背后的代码
gv.DataSource = new[] { new { str = "A" }, new { str = "B" }, new { str = "C" } };
gv.DataBind();
var sqlSource = gv.Rows[2].FindControl("sqlId") as SqlDataSource;
Response.Write(sqlSource.ConnectionString);
这将打印出嵌入式SqlDataSource
的连接字符串。