将列值作为id添加到asp.net中GridView的每一行

时间:2012-08-25 07:19:39

标签: gridview

我正在使用此代码为GridView的每一行提供唯一ID。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   GridViewRow row = e.Row;
   if (row.RowType == DataControlRowType.DataRow)
   {
      row.Attributes["id"] = cRowID.ToString();
      cRowID++;
   }   
}

其中 cRowID 是全局整数变量 此代码为我提供了HTML代码

<table id="gridview1">
 <tr id="1"><td>...</td></tr>
 <tr id="2"><td>...</td></tr>
  .
  .  
 <tr id="n"><td>...</td></tr>
</table>

如何将cRowID替换为添加到同一行的特定列(比如column1)值?

修改
在HTML中添加tr标签的ID后,我希望它成为

<tr id="abc" ><td>abc</td><td>...</td></tr>
<tr id="pqr" ><td>pqr</td><td>...</td></tr>
<tr id="xyz" ><td>xyz</td><td>...</td></tr>

有可能吗?如果是,请解释如何?

2 个答案:

答案 0 :(得分:5)

经过测试试试这个

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
     int counter=1;
     foreach (GridViewRow oItem in GridView1.Rows)
     { 
        counter++;
        oItem.Cells[0].Text = counter.ToString();
        oItem.Attributes.Add("id", "yourvalue");//here you can set row id ie(<tr>)
     }
   }

<强>被修改

foreach (GridViewRow oItem in GridView1.Rows)
     { 
        string getFirstColValue = oItem.Cells[0].Text;
        oItem.Attributes.Add("id", getFirstColvalue );
     }

答案 1 :(得分:0)

您无需经历循环。下面给出的代码工作正常:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string getFirstColValue = e.Row.Cells[0].Text;
        e.Row.Attributes.Add("id", getFirstColvalue );            
    }
}