C# 将鼠标单击事件添加到面板

C# 将鼠标单击事件添加到面板,c#,asp.net,panel,mouseclick-event,C#,Asp.net,Panel,Mouseclick Event,我想将mouseclick事件分配给asp.net面板: protected void Page_Load(object sender, EventArgs e) { Panel p = new Panel(); p.Click += new EventHandler(b_Click);//but, this doesn't compiles correctly } protected void b_Click(object sender, EventArgs e) {

我想将
mouseclick
事件分配给
asp.net面板

protected void Page_Load(object sender, EventArgs e)
{
    Panel p = new Panel();
    p.Click += new EventHandler(b_Click);//but, this doesn't compiles correctly
}
protected void b_Click(object sender, EventArgs e) 
{
     //C#code
}

有没有办法将单击事件添加到面板?

使用jQuery 1.7的鼠标单击事件:

$('#placeholderID').on('click', '#panelID', function(e){ });

下面是使面板可点击并在服务器端处理事件的方法

protected void Page_PreRender(object sender, EventArgs e)
{
    this.Page.ClientScript.GetPostBackEventReference(clickMe, "");
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form["__EVENTTARGET"] == "clickMe")
    {
        ClickMeOnClick();
    }
}
将面板放置在web窗体中

<asp:Panel runat="server" ClientIDMode="Static" ID="clickMe">
    Click here
</asp:Panel>
在服务器端处理事件

protected void Page_PreRender(object sender, EventArgs e)
{
    this.Page.ClientScript.GetPostBackEventReference(clickMe, "");
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form["__EVENTTARGET"] == "clickMe")
    {
        ClickMeOnClick();
    }
}

PreRender事件处理程序中的代码用于asp.net framework在客户端渲染_doPostBack函数。如果您的页面包含导致自动回发的控件,则不需要此代码。

如果您想要更简单的解决方案,请在面板关闭标记前放置一个按钮,使css样式覆盖整个面板,不透明度:0,调整z-index以不覆盖其他元素,只需在代码隐藏中使用onclick方法即可

例如:

css:

asp:


好了,没有javascript和jquery来做这个魔术

asp:Panel
更改为
asp:LinkButton
或将面板包装在LinkButton中。这还可以防止
OnClick
与子控件单击发生冲突,例如
asp:CheckBox

在asp.net中没有面板的单击事件,您可以使用Javascript进行尝试,请参见:
protected void Page_PreRender(object sender, EventArgs e)
{
    this.Page.ClientScript.GetPostBackEventReference(clickMe, "");
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form["__EVENTTARGET"] == "clickMe")
    {
        ClickMeOnClick();
    }
}
btn-panel{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    opacity: 0;
    z-index: -1;
}
<asp:Panel ID="myPanel" runat="server" >

            //all your other elements here...
            <asp:Button ID="Button1" runat="server" Text="" CssClass="btn-panel"
                OnClick="YourButton_Click" />
</asp:Panel>
protected void YourButton_Click(object sender, EventArgs e)
    {
       // Your Code Here...
    }