c# - 可点击的 Web 控件,ASP.NET

标签 c# asp.net button web-controls

这个问题与 my last question 有关如果您需要更多背景信息。

我的问题是:是否可以使 asp.net 表格中的单元格可点击?

或者是否至少可以在 ASP.NET 中制作一个可点击的 WebControl(应该可以放置在 ControlCollection 中),而不是 Button 或 LinkBut​​ton? 如果不能,是否可以将多行信息添加到按钮文本中?

我已经尝试将其他组件添加到按钮的 ControlCollection(我已经看到它在 Button 的 Windows 窗体版本中工作),看看我是否可以将子组件渲染到按钮,但没有成功:

private void ModifyTableCell(TableCell cell)
{
    //Create new button
    Button btnCell = new Button();
    btnCell.Click += (sender, args) =>
    {
        //Event for the button
    };

    //Create new Label
    Label lblCell = new Label();
    lblCell.Font.Bold = true;
    lblCell.Text = "This text won't appear";

    btnCell.Controls.Add(lblCell); //Attempt to add label to Button
    cell.Controls.Add(btnCell);
}

编辑:我最终只是为整个单元格创建了一个多行 LinkBut​​ton。

最佳答案

通过分配 onclick 属性并利用 __doPostBack 函数,您应该能够使几乎所有控件都可点击。

ctrl.Attributes["onclick"] = string.Format("__doPostBack('{0}', '{1}');", ctrl.ClientID, "SomeArgument");

您也可以使用 GetPostBackEventReference 方法。这个选项实际上更安全,因为它将注册尚不存在的 __doPostBack 函数:

ctrl.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(ctrl, string.Empty);

然后,在代码隐藏中,您可以简单地覆盖 RaisePostBackEvent 方法:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    base.RaisePostBackEvent(source, eventArgument);

    if (eventArgument == "SomeArgument") //using the argument
    {
        //do whatever
    }
}

关于c# - 可点击的 Web 控件,ASP.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500019/

相关文章:

c# - 在 asp.net core 3.0 中为角色 SecurityStamp 创建 ClaimsIdentityOptions

matlab - 将按钮添加到 MATLAB 图窗(而非 GUI)以退出循环

c# - 如何在设计时将复杂的属性值从一个用户控件复制到另一个?

c# - 从 git checkout 后 nuget dll 丢失

c# - 域驱动设计中上下文之间的通信

asp.net - 将 RSS pubDate 设置为 .NET DateTime 格式

c# - 使用C#,如何读取动态创建的文本框的内容?

c# - 更改字符串中单词的位置

android - 如何在android中点击相同框架布局中的两个重叠按钮

javascript - div 的关闭按钮,使用 Jquery 访问 ID