根据标签控件值获取gridview的rowindex

时间:2012-11-13 21:35:05

标签: c# asp.net

我的页面上有label controllabel control下面有Gridview。标签控件中存在的值也存在于Gridview中。标签控件具有这样的值

3244|Yellow Ink| Test Link

在gridview中,我的值也是3244

3244    yello Ink   Test Link
3255    Green Link  Test2

一旦页面加载,我希望我的代码中的行索引<3244 。他们是否可以这样做。

3 个答案:

答案 0 :(得分:0)

不知道你拥有什么类型的数据源,其中一种方法就是使用这样的LINQ:

protected void Page_Load(object sender, EventArgs e)
{
    // Fetch the text from your label. (I'm assuming that you have only one label with the text "3244|Yellow Ink| Test Link".
    string text = Label1.Text;

    // Find the first row or return null if not found.
    var resultRow = GridView1.Rows.Cast<GridViewRow>().FirstOrDefault(row =>
    {
        // Get the id (that I'm guessing is the first (0-index) column/cell)
        var id = row.Cells[0].Text;

        // Return true/false if the label text starts with the same id.
        return text.StartsWith(id);
    });

    if (resultRow != null)
    {
        var index = resultRow.RowIndex;
    }
}

较短的版本如下所示:

var resultRow = GridView1.Rows.Cast<GridViewRow>()
    .FirstOrDefault(r => text.StartsWith(r.Cells[0].Text));

答案 1 :(得分:0)

  protected void btnJobAppSelected_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridViewJobApplications.Rows)
    {

        int rowIndex = ((sender as LinkButton).NamingContainer as GridViewRow).RowIndex;

        LinkButton btnJobAppSelected = (LinkButton)GridViewJobApplications.Rows[rowIndex].FindControl("btnJobAppSelected");

    }
}

答案 2 :(得分:0)

在填充gridView之后的页面加载中,您可以这样操作:

   String searchValue = "3244 ";
    int rowIndex = -1;
    foreach (GridViewRow row in GridViewID.Rows)
    {
        if (row.Cells[0].Text.ToString().Equals(searchValue))
        {
            rowIndex = row.RowIndex;
            break;
        }
    }
    int YourIndex = rowIndex;