Monday, 5 March 2012

Customizing SPGridView style (with hover alt rows)

ascx


<style type="text/css">

.GridViewHeaderStyle {
background-color:#c3dde0;
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}

.GridViewAltRowStyle
{
background-color: #F0F8FF;
font-weight: bold;
color: black;
}

.GridRowStyle
{
background-color: #E6E6FA;
font-weight: bold;
color: black;
}

.GridViewAltRowStyle:hover, .GridRowStyle:hover
{
background-color: yellow;
color: black;
font-weight: bold;
}

</style>


<SharePoint:SPGridView ID="myGridView"
runat="server" AutoGenerateColumns="false" >
</SharePoint:SPGridView>




ascx.cs


public partial class SPGridViewTestUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
string[] fields = { "ID","Name","Country","Total"};
foreach (string s in fields)
{
BoundField bf = new BoundField();
bf.DataField = s;
bf.HeaderText = s;
myGridView.Columns.Add(bf);
}


myGridView.GroupField = "Name";
myGridView.AllowGrouping = true;
myGridView.AllowGroupCollapse = true;
myGridView.AlternatingRowStyle.CssClass = "GridViewAltRowStyle";
myGridView.RowStyle.CssClass = "GridRowStyle";

myGridView.DataSource = SelectData();
myGridView.DataBind();

// if this is set before databind, it won't include the column where the grouping is (top left)
foreach (DataControlField dcf in myGridView.Columns)
{
dcf.HeaderStyle.CssClass = "GridViewHeaderStyle";
}
}


public DataTable SelectData()
{
DataTable dataSource = new DataTable();

dataSource.Columns.Add(new DataColumn("ID", Type.GetType("System.Int32")));
dataSource.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
dataSource.Columns.Add(new DataColumn("Country", Type.GetType("System.String")));
dataSource.Columns.Add(new DataColumn("Total", Type.GetType("System.Int32")));

dataSource.Rows.Add(1, "Jack", "USA", 10000);
dataSource.Rows.Add(2, "Jack", "Thailand", 15000);
dataSource.Rows.Add(3, "Jack", "Australia", 5000);
dataSource.Rows.Add(4, "Sam", "USA", 7000);
dataSource.Rows.Add(5, "Sam", "Thailand", 30000);
dataSource.Rows.Add(6, "Sam", "Australia", 8700);
dataSource.Rows.Add(7, "Andy", "USA", 3000);
dataSource.Rows.Add(8, "Andy", "Thailand", 50000);
dataSource.Rows.Add(9, "Andy", "Australia", 25000);

return dataSource;
}
}




How it looks,

2 comments: