我使用sqldatasource调用存储过程创建了一个gridview用户控件。用户控件是在aspx页面上动态创建的,我可以在不传递任何参数的情况下工作。我无法弄清楚如何在用户控件中传递参数。这是代码的最小化版本。
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Survey.ascx.cs" Inherits="AppSurvey" %>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Count" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:TextBox ID="txtAnswerCount" runat="server" Columns="5" MaxLength="5" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^\d+$"
Display="None" SetFocusOnError="true" ControlToValidate="txtAnswerCount" ErrorMessage = "Count values must be entered as integer values." />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:1316 %>" SelectCommand="dbo.usp_Survey" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="Category" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
namespace EUCNET01316
{
public partial class Survey : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["Category"].DefaultValue = ?????;
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
}
**** ASPX Page
protected void Page_Load(object sender, EventArgs e)
{
UserControl ctl = Page.LoadControl("Survey.ascx") as UserControl;
Panel PB = new Panel();
PB.Controls.Add(ctl);
}
答案 0 :(得分:3)
有很多方法可以做到这一点,但这是一个......在用户控件的代码隐藏中,你可以创建一个公共属性来接受你的参数或你将分配给你的sql参数的值:
namespace EUCNET01316
{
public partial class Survey : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["Category"].DefaultValue = MyParameterValue;
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
public string MyParameterValue {get;set;}
}
}
然后在ASPX页面标记中,添加一个指令以引用用户控件:
<%@ Reference Control="~/Usercontrols/Survey.ascx" %>
然后在代码隐藏中,将您的用户控件转换为其类型而不仅仅是&#34; UserControl&#34;
Survey ctl = Page.LoadControl("Survey.ascx") as Survey;
// set the property
ctl.MyParameterValue = "foo";
现在,在您的代码隐藏中,您可以设置在用户控件上创建的属性。只需确保在尝试将控件加载到页面控件集合之前设置属性(此时生命周期将尝试&#34;赶上,&#34;以及您的控件的page_load将在物业被设定之前开火。