JavaScript 获取所点击行中某单元格的内容

原理:

在行绑定时为行添加onclick handler, 并绑定所要显示的单元格内容:

代码如下

复制代码
    <asp:GridView ID="GridView2" AutoGenerateColumns="False" ShowHeader="True" runat="server"
        OnRowDataBound
="GridView1_RowDataBound">
        
<Columns>
            
<asp:BoundField HeaderText="0" DataField="Col0" />
            
<asp:BoundField HeaderText="1" DataField="Col1" />
            
<asp:BoundField HeaderText="2" DataField="Col2" />
            
<asp:BoundField HeaderText="3" DataField="Col3" />
            
<asp:BoundField HeaderText="4" DataField="Col4" />
            
<asp:BoundField HeaderText="5" DataField="Col5" />
            
<asp:TemplateField HeaderText="6">
                
<ItemTemplate>
                    
<asp:Button ID="gridButton" Text="Press Me" runat="server"></asp:Button>
                
</ItemTemplate>
            
</asp:TemplateField>
            
<asp:BoundField HeaderText="7" DataField="Col7" />
            
<asp:BoundField HeaderText="8" DataField="Col8" />
            
<asp:BoundField HeaderText="9" DataField="Col9" />
        
</Columns>
    
</asp:GridView>
复制代码

 

复制代码
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
// The value that we want is in column #9
            string valueText = e.Row.Cells[9].Text;

            
// Find the Button with an ID of "gridButton" (in column #6 of the Grid)
            Button gridButton = (Button)e.Row.Cells[4].FindControl("gridButton");

            
if (gridButton != null)
            {
                
string clickHandler = string.Format("alert('Value in column #9 is {0}", valueText);
                gridButton.Attributes.Add(
"onclick", clickHandler);
            }
        }
    }
复制代码
posted @   LanceZhang  阅读(2095)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示