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>
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);
}
}
}
{
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);
}
}
}