How to set CssClass on button in DataGrid
I have a ButtonColumn in a DataGrid:
<asp:ButtonColumn HeaderText="Edit" ButtonType="PushButton" Text="Edit" />
How do I set it's CSS class?
The only way I can see to do it, is hooking to the RowDataBound event:
Protected Sub dgSchedule_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgSchedule.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
DirectCast(e.Item.Cells(6).Controls(0), Button).CssClass = "confirmButton"
End If
End Sub
I just feel like there must be a neater way. What happens if I add/remove columns, I'll have to come back here and remember to change column 6...
I tried using a TemplateColumn
and a usual asp:Button
- This worked, but then clicking it did not fire the ItemCommand event of the gr开发者_JAVA百科id which I need to fire.
I have resolved this by using a GridView instead of a DataGrid. Actually not sure why I used a DataGrid in the first place.
This gives an additional property ControlStyle-CssClass
e.g.
<asp:ButtonField HeaderText="Edit" ButtonType="Button" Text="Edit" ControlStyle-CssClass="confirmButton" />
You've got two options:
1. You can set the CssClass property of the ButtonColumn:
<asp:ButtonColumn CssClass="myStyle" ...></asp:ButtonColumn>
This will render the following HTML:
<td class="myStyle">
<input type=button name=select ...>
</td>
As you can see, the CSS class is actually applied to the containing element. To style the column, do this:
.myClass
{
/*Your style attributes go here*/
}
And to style the actual button, do this in your CSS:
.myClass INPUT
{
/*Your style attributes go here*/
}
2. Alternatively, you can use a TemplateColumn instead of a ButtonColumn and set the CssClass property of the nested button control:
<asp:TemplateColumn HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="DeleteButton" runat=server Text="Delete" CssClass="myClass" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
The CSS for this is just as you would expect:
.myClass
{
/*Your style attributes go here*/
}
If you need to stick with DataGrid rather than use GridView, one way to solve this problem is to setup an OnItemDataBound
event.
OnItemDataBound="mydatagrid_ItemDataBound"
Then in the code behind you can attached the CSS class to the button as follows:
//ON DATA BIND
protected void mydatagrid_ItemDataBound(object sender, DataGridItemEventArgs e)
if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer) {
Button myButton= (Button)e.Item.Cells[5].Controls[0];
myButton.Attributes["class"] = "buttonClass";
}
}
精彩评论