获取rowdatabound事件中的列标题文本

时间:2013-11-22 04:16:32

标签: asp.net .net

我需要在GridView的rowdatabound事件的DataControlRowType.Data中获取列标题,这是我的方式:

((DataTable)((GridView)sender).DataSource).Columns[i].ColumnName

还有另一个,可能比上面显示的更简洁吗?只是想看看这里。

4 个答案:

答案 0 :(得分:4)

if (e.Row.RowType == DataControlRowType.Header) { 
    LinkButton LnkHeaderText = e.Row.Cells[1].Controls[0] as LinkButton; 
    LnkHeaderText.Text = "Name"; 
}

答案 1 :(得分:1)

protected void gvLista_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            for (int i = 0; i < gvLista.HeaderRow.Cells.Count; i++)
            {
                string cabecera = gvLista.HeaderRow.Cells[i].Text;
                if (cabecera.Equals("ofertaactiva"))
                {

                    int activo = int.Parse(e.Row.Cells[i].Text);
                    if (activo != 1)
                    {
                        e.Row.BackColor = System.Drawing.Color.SandyBrown;
                    }
                    break;
                }
            }
        }

    }

答案 2 :(得分:0)

这是一种方式

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "Date";
    }
 }

但问题是为什么有人想在运行时更改标题名称。

您可以将bound-field与标题名称一起使用,如下所示(需要将自动生成列设置为false)

 <Columns>
     <asp:BoundField DataField="DateField" HeaderText="Date" 
        SortExpression="DateField" />
 </Columns> 

编辑-1

要让列名更改

  var columnName= e.Row.Cells[0].Text ;

答案 3 :(得分:0)

至少在VB.NET 2010中,这种方法存在缺陷 - 出于某种原因(PRB?)e.Row.Cells(x).Text =“”在RowDataBound事件中。

Private Sub gvSymbolList_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvSymbolList.RowDataBound

    If e.Row.RowType = DataControlRowType.Header Then

        Dim i As Integer

        For i = 0 To e.Row.Cells.Count - 1

            Select Case e.Row.Cells(i).Text.ToLower
                Case "symbol"
                    COL_SYMBOL = i
                Case "description"
                    COL_DESCRIPTION = i
                Case "last"
                    COL_CLOSE = i
                Case "change"
                    COL_CHANGE = i
            End Select

        Next

    End If