Get columns count for GridView when using AutoGeneratedColumns is true


When you set AutoGeneratedColumns to true, you cannot access the GridView’s columns.count from either OnRowDataBound or OnRowCreated event. However, you can use  e.Row.Controls.Count instead. Here is a sample for how to change color for some columns and header in a GridView with AutoGeneratedColumns set to true along with how to change header text for some columns.
 
VB.NET:

Protected Sub GridView1_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowDataBound

If e.Row.RowType = DataControlRowType.Header Then

e.Row.BackColor = Drawing.Color.Yellow

For Each c As TableCell In e.Row.Cells

If c.Text = "ID" Then

c.Text =

"ID change to 1…"

End If

If c.Text = "ID2" Then

c.Text =

"ID2 change to 2…"

End If

Next

End If

If e.Row.RowType = DataControlRowType.DataRow Then

For i As Integer = 3 To e.Row.Controls.Count – 1

e.Row.Cells(i).BackColor = Drawing.Color.Yellow

Next

End If

End Sub

Or

Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated

‘Same code as above

End Sub

C#:

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.Header)

{

e.Row.BackColor = System.Drawing.

Color.Yellow;

foreach (TableCell c in e.Row.Cells)

{

if (c.Text == "ID")

{

c.Text =

"ID change to 1…";

}

if (c.Text == "ID2")

{

c.Text =

"ID2 change to 2…";

}

}

}

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

{

for (int i = 3; i <= e.Row.Controls.Count – 1; i++)

{

e.Row.Cells[i].BackColor = System.Drawing.

Color.Yellow;

}

}

}

Or

protected void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)

{

//same code as above;

}

 

 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s