GridView的同一单元格上的多个链接按钮-单击事件未触发-C#

如何解决GridView的同一单元格上的多个链接按钮-单击事件未触发-C#

我在gridview行的同一单元格上创建了​​多个linkbutton。但是,点击事件并未触发。点击事件时,我必须获取在Gridview的RowDataBound中定义的StudentID。

protected void gvStudent_RowDataBound(object sender,GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //loop through the cell.
        for (int j = 1; j < e.Row.Cells.Count; j++)
        {
            string[] arrLinks = null;
            if (!string.IsNullOrEmpty(e.Row.Cells[j].Text.ToString()) && e.Row.Cells[j].Text.ToString() != "&nbsp;")
            {
                arrLinks = e.Row.Cells[j].Text.Split(',');//Rahul-3495,Meera-2323
            }
            if (arrLinks != null)
            {
                for (int i = 0; i < arrLinks.Length; i++)
                {
                    LinkButton btnLink = new LinkButton();
                    string StudentName= (arrLinks[i].Split('-').First()).ToString();//Rahul
                    string StudentID = (arrLinks[i].Split('-').Last()).ToString();//3495
                    btnLink.ID ="btn_" +  StudentID;
                    btnLink.Text = StudentName + "<br>";                                                     
                  //  btnLink.Click += new EventHandler(StudentButtonsclick);
                     btnLink.CommandName = "btnLink"; 
                    e.Row.Cells[j].Controls.Add(btnLink);
                } 
            }
        }
    }     
}
protected void gvStudent_RowCommand(sender s,GridViewCommandEventArgs e)
{
    if (e.CommandName == "btnLink")
    { }
}
 <asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="true"  
 CssClass="gridview_alter" 
 OnRowDataBound="gvStudent_RowDataBound" OnRowCommand="gvStudent_RowCommand">           
</asp:GridView>

解决方法

我建议为CommandName使用OnRowCommandGridView事件。这是您应该如何做:

protected void gvStudent_RowDataBound(object sender,GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //loop through the cell.
        for (int j = 1; j < e.Row.Cells.Count; j++)
        {
            string[] arrLinks = null;
            if (!string.IsNullOrEmpty(e.Row.Cells[j].Text.ToString()) && e.Row.Cells[j].Text.ToString() != "&nbsp;")
            {
                arrLinks = e.Row.Cells[j].Text.Split(',');//Rahul-3495,Meera-2323
            }
            if (arrLinks != null)
            {
                for (int i = 0; i < arrLinks.Length; i++)
                {
                    LinkButton btnLink = new LinkButton();
                    string StudentName= (arrLinks[i].Split('-').First()).ToString();//Rahul
                    string StudentID = (arrLinks[i].Split('-').Last()).ToString();//3495
                    btnLink.ID = "btn_" + StudentID; // Good to concatenate a string instead just a number in the ID.
                    btnLink.Text = StudentName + "<br>";                                                     
                    btnLink.CommandName = "btnLink"; // Add a CommandName
                    e.Row.Cells[j].Controls.Add(btnLink);
                } 
            }
        }
    }     
}
protected void GridView1_RowCommand(sender s,GridViewCommandEventArgs e)
{
    if (e.CommandName == "btnLink")
    {
        // Link Button was clicked. 
        var linkButton = (LinkButton)sender;
        if (linkButton != null)
        {
            var studentId = linkButton.ID.Replace("btn_",""); // Remove the concatenated string from the id.
            // Do stuff with the student id.
            // I would highly not recommend getting the id from a button element,as it could be modified using browser inspect elements. Instead use,GridView DataKeys.
        }
    }
}

您还应该在RowCommand中添加GridView事件以使其继续进行。例如:

<asp:GridView runat="server" ID="GridView1" OnRowCommand="GridView1_RowCommand">
    <!-- Rest of the elements -->
</asp:GridView>
,

好吧,问题在于,需要在呈现页面后“创建”事件的控件无法真正连接起来。您将不得不将代码移至更早的事件。因此,您可以自由添加控件,但是在大多数情况下,它们将被渲染得太晚而无法附加事件。因此,当您单击链接按钮时,不会触发任何事情。

所以我可以想到两种解决方案。

首先,将控件设置为具有回发URL,并在该回发中包含一个参数。

例如:

Dim lnkBtn As New LinkButton
lnkBtn.Text = "<br/>L" & I
lnkBtn.ID = "cL" & I
lnkBtn.PostBackUrl = "~/GridTest.aspx?r=" & bv.RowIndex

如果放置了PostbackUrl,则在单击按钮时,页面将回发。但是,网格行事件(例如rowindex更改或行单击事件等)将不会触发。因此,如果您希望将参数传递回与上述相同的页面,则可以传递每个控件具有的1-3(或1-N)值。

当然,这意味着您现在在网页URL上有了一个参数(用户会看到此信息)。当然,您只需使用标准的页面加载即可获取参数值

        Request.QueryString["ID"] or whatever.

但是,另一种方法-我认为更好的方法是简单地在js中连接一个OnClickClick()事件,然后执行以下操作:

  I = 1 to N
  Dim lnkBtn As New LinkButton
  lnkBtn.Text = "<br/>L" & I
  lnkBtn.ID = "cL" & I
  lnkBtn.OnClientClick = "mycellclick(" & I & ");return false;"

现在在上面请注意我如何将“ I”传递给js例程。您可以传递200、300或任何您想要的值。

然后您的脚本将如下所示:

<script>
    function mycellclick(e) {
        __doPostBack("MySelect",e);
    }
</script>

因此,上面仅采用了从单元格click(和linkbutn)传递的值,然后使用dopostback进行回发。我使用了“ MySelect”,您可以给它指定任何名称。

现在,在on-load事件中,您可以像这样:

 If Request("__EVENTTARGET") = "MySelect" Then
    Dim mypassvalue As String = Request("__EVENTARGUMENT").ToString
    Debug.Print("row sel for MySelect = " & mypassvalue)
 End If

因此,您是100%正确的-单击这些控件不会触发服务器端事件,并且它们的连接时间太晚,无法发生。因此您可以并且经常说到网格视图中添加一些列或控件,但是它们的创建和渲染太晚了,无法将事件连接起来(因此单击时它们不会触发)。

但是,您可以向lnkbutton添加回发,还可以添加OnClickClick()事件(JavaScript函数调用),它们都将起作用。我不喜欢单击时出现的URL中的参数,因此我认为上述js脚本调用效果很好。

因此,在注释中,我指出(并建议)您必须设置CommandName =“ Select”。这个建议仍然成立(没有CommandName = select,那么rowindex不会触发。您不能只使用任何名称-必须选择它。但是,这仅适用于控件是网格的一部分且不会动态添加的情况)如前所述,有可能将网格事件移至“较早的”事件(页面初始化),但这将是一个挑战,将需要您重新组织页面。网址中的参数会添加js OnClientClick()事件,但是您可以设置控件postbackurl以及网址中的参数,并且如果您打开带有参数的网址也可以很好地工作(我不喜欢它们)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-