In order to add a BoundField dynamically in the code-behind (this example is in VB, but similar for C#), you can use the following snippet:
bf = New BoundField()
bf.DataField = "FieldName"
bf.HeaderText = "Header"
bf.SortExpression = "FieldName(could be different)"
bf.ItemStyle.CssClass = "NoWrap"
MyGrid.Columns.Add(bf)
If you wish to make the CssClass attribute data-dependent, you would require a TemplateField. For instance:
tf = New WebControls.TemplateField()
tf.HeaderText = "Whatever"
tf.SortExpression = "Whatever"
tf.ItemTemplate = New MyItemTemplate("DataField", "CssDataField")
AssessmentGrid.Columns.Add(tf)
The MyItemTemplate class implements the ITemplate interface, which could be found in the App_Code folder. Here's an example:
Imports Microsoft.VisualBasic
Public Class MyItemTemplate
Implements System.Web.UI.ITemplate
Dim DataField1 As String
Dim DataField2 As String
Sub New(ByVal Field1 As String, ByVal Field2 As String)
DataField1 = Field1
DataField2 = Field2
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) _
Implements System.Web.UI.ITemplate.InstantiateIn
Dim ml As New Label()
ml.ID = DataField1
ml.Text = ""
ml.CssClass = ""
AddHandler ml.DataBinding, New EventHandler(AddressOf Item_DataBinding)
container.Controls.Add(l)
End Sub
Protected Sub Item_DataBinding(ByVal sender As Control, ByVal e As System.EventArgs)
Dim bound_value_object As Object
Dim data_item_container As IDataItemContainer = sender.NamingContainer
Dim Parent As TableCell = sender.Parent
Dim l As Label = sender
bound_value_object = DataBinder.Eval(data_item_container.DataItem, DataField1)
l.Text = bound_value_object.ToString
bound_value_object = DataBinder.Eval(data_item_container.DataItem, DataField2)
Parent.CssClass = bound_value_object.ToString
End Sub
End Class
You could also directly apply the CssClass to the label itself, but the original question specified it should be on the cell.