GridView识别点击的行值?

时间:2011-12-29 13:10:25

标签: c# asp.net linq gridview

我有这个gridview:

<div class="content">
    <asp:GridView ID="DocumentGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="DocumentGrid_RowCommand" >
        <Columns>
            <asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
            <asp:ButtonField HeaderText="Download Link" Text="Download"/>
        </Columns>
    </asp:GridView>
</div>

如您所见,按下“下载”按钮时会调用DocumentGrid_RowCommand,如何找出所单击行的值是什么?

2 个答案:

答案 0 :(得分:1)

如果GridView中有多个按钮字段,请设置CommandName属性。这样我们就可以确定在RowCommand事件中按下了哪个按钮。所以总是设置commandName属性。

<Columns>
 <asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
 <asp:ButtonField HeaderText="Download Link" Text="Download" CommandName="cmd"/>
</Columns>

RowCommand事件处理程序中,GridViewCommandEventArgs.CommandArgument属性返回按下按钮的行的索引。

 protected void DocumentGrid_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmd")
        {
            int index = int.Parse(e.CommandArgument.ToString());
            GridViewRow row = DocumentGrid.Rows[index];
            if (row.RowType == DataControlRowType.DataRow)
            {
                Response.Write(row.Cells[0].Text);
            }
        }
    }

答案 1 :(得分:1)

如果你设置这样的标记,

        <Columns>
            <asp:TemplateField HeaderText="Download">
                <ItemTemplate>
                    <asp:Button ID="btnDownload" CommandName="Download" CommandArgument='<%# Container.DataItemIndex %>'
                        runat="server" Text="Download" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
关于代码隐藏的

,您可以像这样检查CommandArgument

if (e.CommandName == "Download")
{
    int index = Convert.ToInt32(e.CommandArgument);
}