简体   繁体   English

如果我有来自此行的单元格值,请在Asp.net的GridView控件中获取行的索引。

[英]Get index of row in GridView Control in Asp.net if i have a value of a cell from this row.?

I Have add a grid view control in my form and fill by the DataTable. 我在表单中添加了一个网格视图控件,并通过DataTable进行填充。 And I create first column of every row as a link button and set same onclick event. 我将每一行的第一列创建为链接按钮,并设置相同的onclick事件。 Then I can get the text of this linkbutton. 然后,我可以获得此链接按钮的文本。

<asp:TemplateField HeaderText="DocName">
    <ItemTemplate>
        <asp:LinkButton ID="DocName" runat="server" Text='<%# Eval("DocName") %>' OnClick="DocNameClick"></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

I want to get the whole row if user click the linkbutton of any row in the click event. 如果用户单击click事件中任一行的链接按钮,我希望获得整行。

protected void DocNameClick(object sender, EventArgs e)
 {
     LinkButton btn = (LinkButton)sender;
     string name = btn.Text;
 }

You get the GridViewRow (hence all other controls in this TemplateField via FindControl ) by casting the NamingContainer propertery of the button: 通过对按钮的NamingContainer属性进行强制转换,可以得到GridViewRow (因此可以通过FindControl在此TemplateField使用所有其他控件):

protected void DocNameClick(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)sender;
    GridViewRow row = (GridViewRow) btn.NamingContainer;
    // use row.FindControl("ControlID") to get controls in other columns ...
    int rowIndex = row.RowIndex;
    string name = btn.Text;
}
protected void DocNameClick(object sender, System.EventArgs e)
{
    LinkButton btn = (LinkButton)sender;
    //Get the row that contains this button
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

You can get row index by following code 您可以通过以下代码获取行index

LinkButton btn = (LinkButton)sender;
GridViewRow row = btn.NamingContainer as GridViewRow ;
int index = row.RowIndex;

Add to you link the commandargument 添加到您的链接命令参数

CommandArgument='<%# Container.DataItemIndex%>' 

And in your method use it 并在您的方法中使用它

protected void DocNameClick(object sender, EventArgs e)
{
    LinkButton btn = sender as LinkButton;
    string name = btn.Text;
    if(!String.IsNullOrEmpty(name))
        int index = int.Parse(e.CommandArgument);
}

Edit: int parse on commandargument 编辑:在命令参数上进行int解析

Try this: 尝试这个:

protected void DocName_Click(object sender, EventArgs e)
{
    LinkButton btn = sender as LinkButton;
    string name = btn.Text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM