首页 > 解决方案 > 如何处理用户控件网格视图的事件?

问题描述

我有一个用户控件作为网格视图。我正在动态添加它...我已经为数据源创建了方法,但是我无法使用网格视图的其他事件,例如“Row_Data_Bound”等。

我在网上看到了代码,上面写着创建代表并添加以下内容

protected void Simple_DGV_RowDataBound(object sender, GridViewRowEventArgs e)   
{
OnRowDataBound(e);
}

但我在这里收到一个错误,说当前上下文中不存在名称 OnRowDataBound

谁能帮助我访问父页面中的用户控件网格视图的事件

编辑:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs" Inherits="ProjectManagement.UserControl.User1" %>
<div>
<asp:GridView ID="ucGridView" runat="server" SkinID="gvSchedulerSkin" AllowSorting="false" OnRowDataBound="ucGridView_RowDataBound">
   <RowStyle Width="20px" /> 
</asp:GridView>
</div>

这是我的 ascx 页面...我想在多个地方(在运行时)使用此网格视图,所以我创建了一个用户控件...基本上我想从我的代码中调用此用户控件,然后使用它的rowdatabound我想将数据与gridview绑定..

我在网站上看到它说使用事件冒泡......但我不知道如何实现它。

所以你能在这件事上帮忙吗..这样我就可以像我一样正常使用rowdatabound

提前谢谢

标签: c#asp.netgridviewuser-controls

解决方案


我在本地创建了一个项目,这没关系。

我有一个名为 TestUserControl.ascx 的控件。我在设计模式下将 GridView 控件拖到用户控件上,并将其命名为“grdControlsGrid”。

这产生了以下标记。

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUserControl.ascx.cs" Inherits="TestASPNet.TestUserControl" %>
<asp:GridView ID="grdControlsGrid" runat="server">
</asp:GridView>

然后我通过在 runat="server" 之后将“OnRowDataBound=" 输入到 hmtl 来添加事件 OnRowDataBound。当您点击 equals 时,您可以选择为此事件创建方法。双击“创建方法”选项,这将为您将事件连接到方法。

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUserControl.ascx.cs" Inherits="TestASPNet.TestUserControl" %>
<asp:GridView ID="grdControlsGrid" runat="server" OnRowDataBound="grdControlsGrid_OnRowDataBound">
</asp:GridView>

根据下面的代码,此代码现在驻留在您的用户控件中。

或者,您可以在用户控件加载中自行连接事件。

 public partial class TestUserControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Manually Add event handler
            grdControlsGrid.RowDataBound += GrdControlsGrid_RowDataBound;
        }

        private void GrdControlsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Manually bound event
        }

        protected void grdControlsGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Auto wired event
        }
    }

出于某种原因,当通过标记自动连接时,您会得到事件“OnRowDataBound”.. 但是当在后面的代码中手动完成时,您会得到“RowDataBound”。我的猜测是它们是相同的..但也许其他人可以阐明这一点。

希望有帮助。


推荐阅读