Styling a Gridview “Caption” from C# class

狂风中的少年 提交于 2019-12-23 18:47:31

问题


I'm trying to style the caption of a ASP.Net GridView in a C# file. here is my method that returns a styled GridView:

private GridView setupGridView(string caption)
{
 var gview = new GridView()
 {
  BackColor = Color.White,
  BorderColor = Color.Gray,
  BorderStyle = BorderStyle.Solid,
  BorderWidth = new Unit(1, UnitType.Pixel),
  Caption = caption,
  ForeColor = Color.Black,
 };
 gview.HeaderStyle.BackColor = Color.Navy;
 gview.HeaderStyle.ForeColor = Color.White;
 gview.HeaderStyle.BorderColor = Color.DarkGray;
 gview.HeaderStyle.BorderWidth = new Unit(1, UnitType.Pixel);
 gview.HeaderStyle.BorderStyle = BorderStyle.Solid;
 gview.AlternatingRowStyle.BackColor = Color.LightGray;
 return gview;
}

By default the Caption is not styled (it's just black text on top of the gridview)

Does anyone know how I can style the Caption Navy with white text? (similar to the way I have styled the header row maybe?)

EDIT: I've done this before by using CSS, but I don't have the liberty of doing that as, this is a program that generates gridviews to send in an email. There is no aspx file or skin...


回答1:


So after talking with another developer, we came up with this. (BTW I'm kicking myself because it is so simple)

To write out the gridview for sending in the email, I was using an htmlwriter like so:

var sbuilder = new StringBuilder();
var swriter = new StringWriter(sbuilder);
var htmlWriter = new HtmlTextWriter(swriter);
//...
myGridview.RenderControl(htmlwriter);
mymailMessage.Body = sbuilder.ToString();

All I had to do was add the styles before using the htmlwriter to render the controls.

So I added this after creating the htmlwriter

htmlWriter.Write("<style type=\"text/css\">caption { font-family: Arial, sans-serif; color: white; font-size: 14px; font-weight: bold; padding: 3px 100px 3px 7px; text-align: left; white-space: nowrap; text-align: center; background-color: navy;}</style>");

Now of course I will put this string in a config file somewhere, so I don't have to recompile the project to change the style of the email, but this is all I needed to do.

Wala! all captions are styled the same...




回答2:


if you use gview.HeaderRow instead of gview.HeaderStyle then it will work. Try:

gview.HeaderRow.ForeColor = Drawing.Color.White

This will add the inline style to the table-row (tr) so it can be used in html-formatted email.



来源:https://stackoverflow.com/questions/3858494/styling-a-gridview-caption-from-c-sharp-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!