16 个解决方案
#1
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace DataGridCellFormatting
{
/// <summary>
/// Form2 的摘要说明。
/// </summary>
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form2()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 56);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(536, 296);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(560, 389);
this.Controls.Add(this.dataGrid1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void FormatGridCells(object sender, DataGridFormatCellEventArgs e)
{
//color row 1 red
if(e.Row == 0)
e.BackBrush = Brushes.Red;
if(e.Row == 1)
e.BackBrush = Brushes.Red;
if(e.Row == 2)
e.BackBrush = Brushes.Red;
if(e.Row == 3)
e.BackBrush = Brushes.Red;
//color column 4 blue
// if(e.Column == 4)
// e.BackBrush = Brushes.Blue;
//
// //set font of some cells to bold
// if( (e.Row + e.Column) % 5 == 0 )
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold);
//
// //set textcolor of some cells to blue
// if( (e.Row + e.Column) % 8 == 0 )
// e.ForeBrush = Brushes.DodgerBlue;
//
// //set font of some cells to bold, underline, italic with white text on green background
// if( (e.Row + e.Column) % 9 == 0 )
// {
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);
// e.ForeBrush = Brushes.White;
// e.BackBrush = Brushes.Green;
// }
}
private DataTable SomeDataTable()
{
DataTable dt = new DataTable("MyTable");
//add some columns
int nCols = 10;
for(int j = 0; j < nCols; ++j)
dt.Columns.Add(new DataColumn(string.Format("col{0}", j), typeof(string)));
//add some rows
int nRows = 40;
for(int i = 0; i < nRows; ++i)
{
DataRow dr = dt.NewRow();
for(int j = 0; j < nCols; ++j)
dr[j] = string.Format("row {0} col {1}", i, j);
dt.Rows.Add(dr);
}
dt.DefaultView.AllowNew = false;//turn off append row
return dt;
}
private void AddCellFormattingColumnStyles(DataGrid grid, FormatCellEventHandler handler)
{
DataGridTableStyle ts = new DataGridTableStyle();
DataTable dt = (DataTable) grid.DataSource;
ts.MappingName = dt.TableName;
for(int j = 0; j < dt.Columns.Count; ++j)
{
DataGridFormattableTextBoxColumn cs = new DataGridFormattableTextBoxColumn(j);
cs.MappingName = dt.Columns[j].ColumnName;
cs.HeaderText = dt.Columns[j].ColumnName;
cs.SetCellFormat += handler;
ts.GridColumnStyles.Add(cs);
}
grid.TableStyles.Clear();
grid.TableStyles.Add(ts);
}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
}
private void Form2_Load(object sender, System.EventArgs e)
{
this.dataGrid1.DataSource = SomeDataTable();
AddCellFormattingColumnStyles(this.dataGrid1, new FormatCellEventHandler(FormatGridCells));
}
public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e);
public class DataGridFormatCellEventArgs : EventArgs
{
private int _column;
private int _row;
private Font _font;
private Brush _backBrush;
private Brush _foreBrush;
private bool _useBaseClassDrawing;
public DataGridFormatCellEventArgs(int row, int col, Font font1, Brush backBrush, Brush foreBrush)
{
_row = row;
_column = col;
_font = font1;
_backBrush = backBrush;
_foreBrush = foreBrush;
_useBaseClassDrawing = false;
}
public int Column
{
get{ return _column;}
set{ _column = value;}
}
public int Row
{
get{ return _row;}
set{ _row = value;}
}
public Font TextFont
{
get{ return _font;}
set{ _font = value;}
}
public Brush BackBrush
{
get{ return _backBrush;}
set{ _backBrush = value;}
}
public Brush ForeBrush
{
get{ return _foreBrush;}
set{ _foreBrush = value;}
}
public bool UseBaseClassDrawing
{
get{ return _useBaseClassDrawing;}
set{ _useBaseClassDrawing = value;}
}
}
public class DataGridFormattableTextBoxColumn : DataGridTextBoxColumn
{
//in your handler, set the EnableValue to true or false, depending upon the row & col
public event FormatCellEventHandler SetCellFormat;
private int _col;
public DataGridFormattableTextBoxColumn(int col)
{
_col = col;
}
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush);
if(SetCellFormat != null)
{
SetCellFormat(this, e);
}
if(e.UseBaseClassDrawing)
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
else
{
g.FillRectangle(e.BackBrush, bounds);
g.DrawString(this.GetColumnValueAtRow(source, rowNum).ToString(), e.TextFont, e.ForeBrush, bounds.X, bounds.Y);
}
if(e.TextFont != this.DataGridTableStyle.DataGrid.Font)
e.TextFont.Dispose();
}
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//comment to make cells unable to become editable
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}
}
}
}
只需要改变FormatGridCells中的行就行了
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace DataGridCellFormatting
{
/// <summary>
/// Form2 的摘要说明。
/// </summary>
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form2()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 56);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(536, 296);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(560, 389);
this.Controls.Add(this.dataGrid1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void FormatGridCells(object sender, DataGridFormatCellEventArgs e)
{
//color row 1 red
if(e.Row == 0)
e.BackBrush = Brushes.Red;
if(e.Row == 1)
e.BackBrush = Brushes.Red;
if(e.Row == 2)
e.BackBrush = Brushes.Red;
if(e.Row == 3)
e.BackBrush = Brushes.Red;
//color column 4 blue
// if(e.Column == 4)
// e.BackBrush = Brushes.Blue;
//
// //set font of some cells to bold
// if( (e.Row + e.Column) % 5 == 0 )
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold);
//
// //set textcolor of some cells to blue
// if( (e.Row + e.Column) % 8 == 0 )
// e.ForeBrush = Brushes.DodgerBlue;
//
// //set font of some cells to bold, underline, italic with white text on green background
// if( (e.Row + e.Column) % 9 == 0 )
// {
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);
// e.ForeBrush = Brushes.White;
// e.BackBrush = Brushes.Green;
// }
}
private DataTable SomeDataTable()
{
DataTable dt = new DataTable("MyTable");
//add some columns
int nCols = 10;
for(int j = 0; j < nCols; ++j)
dt.Columns.Add(new DataColumn(string.Format("col{0}", j), typeof(string)));
//add some rows
int nRows = 40;
for(int i = 0; i < nRows; ++i)
{
DataRow dr = dt.NewRow();
for(int j = 0; j < nCols; ++j)
dr[j] = string.Format("row {0} col {1}", i, j);
dt.Rows.Add(dr);
}
dt.DefaultView.AllowNew = false;//turn off append row
return dt;
}
private void AddCellFormattingColumnStyles(DataGrid grid, FormatCellEventHandler handler)
{
DataGridTableStyle ts = new DataGridTableStyle();
DataTable dt = (DataTable) grid.DataSource;
ts.MappingName = dt.TableName;
for(int j = 0; j < dt.Columns.Count; ++j)
{
DataGridFormattableTextBoxColumn cs = new DataGridFormattableTextBoxColumn(j);
cs.MappingName = dt.Columns[j].ColumnName;
cs.HeaderText = dt.Columns[j].ColumnName;
cs.SetCellFormat += handler;
ts.GridColumnStyles.Add(cs);
}
grid.TableStyles.Clear();
grid.TableStyles.Add(ts);
}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
}
private void Form2_Load(object sender, System.EventArgs e)
{
this.dataGrid1.DataSource = SomeDataTable();
AddCellFormattingColumnStyles(this.dataGrid1, new FormatCellEventHandler(FormatGridCells));
}
public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e);
public class DataGridFormatCellEventArgs : EventArgs
{
private int _column;
private int _row;
private Font _font;
private Brush _backBrush;
private Brush _foreBrush;
private bool _useBaseClassDrawing;
public DataGridFormatCellEventArgs(int row, int col, Font font1, Brush backBrush, Brush foreBrush)
{
_row = row;
_column = col;
_font = font1;
_backBrush = backBrush;
_foreBrush = foreBrush;
_useBaseClassDrawing = false;
}
public int Column
{
get{ return _column;}
set{ _column = value;}
}
public int Row
{
get{ return _row;}
set{ _row = value;}
}
public Font TextFont
{
get{ return _font;}
set{ _font = value;}
}
public Brush BackBrush
{
get{ return _backBrush;}
set{ _backBrush = value;}
}
public Brush ForeBrush
{
get{ return _foreBrush;}
set{ _foreBrush = value;}
}
public bool UseBaseClassDrawing
{
get{ return _useBaseClassDrawing;}
set{ _useBaseClassDrawing = value;}
}
}
public class DataGridFormattableTextBoxColumn : DataGridTextBoxColumn
{
//in your handler, set the EnableValue to true or false, depending upon the row & col
public event FormatCellEventHandler SetCellFormat;
private int _col;
public DataGridFormattableTextBoxColumn(int col)
{
_col = col;
}
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush);
if(SetCellFormat != null)
{
SetCellFormat(this, e);
}
if(e.UseBaseClassDrawing)
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
else
{
g.FillRectangle(e.BackBrush, bounds);
g.DrawString(this.GetColumnValueAtRow(source, rowNum).ToString(), e.TextFont, e.ForeBrush, bounds.X, bounds.Y);
}
if(e.TextFont != this.DataGridTableStyle.DataGrid.Font)
e.TextFont.Dispose();
}
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//comment to make cells unable to become editable
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}
}
}
}
只需要改变FormatGridCells中的行就行了
#2
我up
#3
o,yeah ,也太详细了吧,不错!
#4
也可以直接设置页面文件:
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 296px" runat="server" Height="104px" Width="713px" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" AllowPaging="True" PageSize="3" AutoGenerateColumns="False">
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999">
</SelectedItemStyle>
<ItemStyle ForeColor="#000066"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="userid" DataNavigateUrlFormatString="" DataTextField="userid" SortExpression="userid" HeaderText="用户ID">
</asp:HyperLinkColumn>
<asp:BoundColumn DataField="name" HeaderText="名称">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="gender" HeaderText="性别">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="email" HeaderText="EMAIL">
<HeaderStyle Width="35%"></HeaderStyle>
</asp:BoundColumn>
</Columns>
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 296px" runat="server" Height="104px" Width="713px" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" AllowPaging="True" PageSize="3" AutoGenerateColumns="False">
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999">
</SelectedItemStyle>
<ItemStyle ForeColor="#000066"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="userid" DataNavigateUrlFormatString="" DataTextField="userid" SortExpression="userid" HeaderText="用户ID">
</asp:HyperLinkColumn>
<asp:BoundColumn DataField="name" HeaderText="名称">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="gender" HeaderText="性别">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="email" HeaderText="EMAIL">
<HeaderStyle Width="35%"></HeaderStyle>
</asp:BoundColumn>
</Columns>
#5
因为我最近转.NET就碰到这样的需求,我研究了一下,基本可以满足要求,希望对各位有所帮助,
楼主记得给分啊
楼主记得给分啊
#6
顶,接点分^_^
无聊就接分来了
无聊就接分来了
#7
OK,寫的非常好.无聊來了.
#8
我晕!
tkx222(tkx) !!这个问题有必要回答的这么详细不?
唉! 接分狂!!
太想分了吧
tkx222(tkx) !!这个问题有必要回答的这么详细不?
唉! 接分狂!!
太想分了吧
#9
看得狂晕,呵呵。支持热情!
#10
我支持一楼的兄弟,只有这样才好
#11
利用DataGrid的ItemStyle样式
<asp:DataGrid
ID="..."
ItemStyle-BackColor="Blue"
ItemStyle-Color="Red"
Runat="Server"/>
...
<asp:DataGrid
ID="..."
ItemStyle-BackColor="Blue"
ItemStyle-Color="Red"
Runat="Server"/>
...
#12
我下面有一個例子,希望對你有幫助...
datagrid 的樣式表(DataGridTableStyle)應用...
首先 我們先定一個 datatable 和 一個datarow
Private idtb_temp As New DataTable
Private idrw_row As DataRow
private sub GetDataTable()
idtb_temp.Columns.Add("prdodr_subodr_code") '''定義datatable 的列名
idtb_temp.TableName = "SearchTable"
Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn
Dim ldgts_styles As New Windows.Forms.DataGridTableStyle
ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow
'''選中行的前景色,即字體顏色
ldgts_styles.SelectionBackColor = System.Drawing.Color.Brown '''選中行的背景色
ldgts_styles.ForeColor = System.Drawing.Color.Coral
''' datagrid 中將要顯示的字的顏色
ldgts_styles.AlternatingBackColor = System.Drawing.Color.Cyan
'''datagrid中奇數行所顯示的顏色
ldgts_styles.BackColor = System.Drawing.Color.Cyan
'''datagrid中偶數行所顯示的顏色
ldgts_styles.AllowSorting = False
'''些樣式表定義datagrid不允許自動排序..
ldgts_styles.MappingName = "SearchTable"
ldcl_header = New Windows.Forms.DataGridTextBoxColumn
'''實例化一個datagridtextboxcolumn
ldcl_header.MappingName = "prdodr_subodr_code"
'''引用前面定義的 “列名”
ldcl_header.HeaderText = "第一列"
'''datagrid 中顯示的 表列頭 文字
ldcl_header.ReadOnly = True '''些列設定為只讀
ldcl_header.TextBox.BorderStyle = BorderStyle.Fixed3D
ldcl_header.TextBox.ForeColor = System.Drawing.Color.Red
ldgts_styles.GridColumnStyles.Add(ldcl_header)
For i As Integer = 0 To 7
idrw_row = idtb_temp.NewRow
idrw_row.Item("prdodr_subodr_code") = "第" & i & "行"
idtb_temp.Rows.Add(idrw_row)
Next
idtb_temp.DefaultView.AllowNew = False
Me.DataGrid1.TableStyles.Add(ldgts_styles)
Me.DataGrid1.DataSource = idtb_temp
end sub
datagrid 的樣式表(DataGridTableStyle)應用...
首先 我們先定一個 datatable 和 一個datarow
Private idtb_temp As New DataTable
Private idrw_row As DataRow
private sub GetDataTable()
idtb_temp.Columns.Add("prdodr_subodr_code") '''定義datatable 的列名
idtb_temp.TableName = "SearchTable"
Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn
Dim ldgts_styles As New Windows.Forms.DataGridTableStyle
ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow
'''選中行的前景色,即字體顏色
ldgts_styles.SelectionBackColor = System.Drawing.Color.Brown '''選中行的背景色
ldgts_styles.ForeColor = System.Drawing.Color.Coral
''' datagrid 中將要顯示的字的顏色
ldgts_styles.AlternatingBackColor = System.Drawing.Color.Cyan
'''datagrid中奇數行所顯示的顏色
ldgts_styles.BackColor = System.Drawing.Color.Cyan
'''datagrid中偶數行所顯示的顏色
ldgts_styles.AllowSorting = False
'''些樣式表定義datagrid不允許自動排序..
ldgts_styles.MappingName = "SearchTable"
ldcl_header = New Windows.Forms.DataGridTextBoxColumn
'''實例化一個datagridtextboxcolumn
ldcl_header.MappingName = "prdodr_subodr_code"
'''引用前面定義的 “列名”
ldcl_header.HeaderText = "第一列"
'''datagrid 中顯示的 表列頭 文字
ldcl_header.ReadOnly = True '''些列設定為只讀
ldcl_header.TextBox.BorderStyle = BorderStyle.Fixed3D
ldcl_header.TextBox.ForeColor = System.Drawing.Color.Red
ldgts_styles.GridColumnStyles.Add(ldcl_header)
For i As Integer = 0 To 7
idrw_row = idtb_temp.NewRow
idrw_row.Item("prdodr_subodr_code") = "第" & i & "行"
idtb_temp.Rows.Add(idrw_row)
Next
idtb_temp.DefaultView.AllowNew = False
Me.DataGrid1.TableStyles.Add(ldgts_styles)
Me.DataGrid1.DataSource = idtb_temp
end sub
#13
tkx222(tkx)
好好好!!!
好好好!!!
#14
支持tkx222(tkx)
#15
TO:tkx222(tkx)
这段代码有个问题,我排序之后原有的数据顺序变了,而颜色还是在前面几行,这是不是有点不符合?
这段代码有个问题,我排序之后原有的数据顺序变了,而颜色还是在前面几行,这是不是有点不符合?
#16
支持一楼的师傅,有时间教教我
#1
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace DataGridCellFormatting
{
/// <summary>
/// Form2 的摘要说明。
/// </summary>
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form2()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 56);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(536, 296);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(560, 389);
this.Controls.Add(this.dataGrid1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void FormatGridCells(object sender, DataGridFormatCellEventArgs e)
{
//color row 1 red
if(e.Row == 0)
e.BackBrush = Brushes.Red;
if(e.Row == 1)
e.BackBrush = Brushes.Red;
if(e.Row == 2)
e.BackBrush = Brushes.Red;
if(e.Row == 3)
e.BackBrush = Brushes.Red;
//color column 4 blue
// if(e.Column == 4)
// e.BackBrush = Brushes.Blue;
//
// //set font of some cells to bold
// if( (e.Row + e.Column) % 5 == 0 )
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold);
//
// //set textcolor of some cells to blue
// if( (e.Row + e.Column) % 8 == 0 )
// e.ForeBrush = Brushes.DodgerBlue;
//
// //set font of some cells to bold, underline, italic with white text on green background
// if( (e.Row + e.Column) % 9 == 0 )
// {
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);
// e.ForeBrush = Brushes.White;
// e.BackBrush = Brushes.Green;
// }
}
private DataTable SomeDataTable()
{
DataTable dt = new DataTable("MyTable");
//add some columns
int nCols = 10;
for(int j = 0; j < nCols; ++j)
dt.Columns.Add(new DataColumn(string.Format("col{0}", j), typeof(string)));
//add some rows
int nRows = 40;
for(int i = 0; i < nRows; ++i)
{
DataRow dr = dt.NewRow();
for(int j = 0; j < nCols; ++j)
dr[j] = string.Format("row {0} col {1}", i, j);
dt.Rows.Add(dr);
}
dt.DefaultView.AllowNew = false;//turn off append row
return dt;
}
private void AddCellFormattingColumnStyles(DataGrid grid, FormatCellEventHandler handler)
{
DataGridTableStyle ts = new DataGridTableStyle();
DataTable dt = (DataTable) grid.DataSource;
ts.MappingName = dt.TableName;
for(int j = 0; j < dt.Columns.Count; ++j)
{
DataGridFormattableTextBoxColumn cs = new DataGridFormattableTextBoxColumn(j);
cs.MappingName = dt.Columns[j].ColumnName;
cs.HeaderText = dt.Columns[j].ColumnName;
cs.SetCellFormat += handler;
ts.GridColumnStyles.Add(cs);
}
grid.TableStyles.Clear();
grid.TableStyles.Add(ts);
}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
}
private void Form2_Load(object sender, System.EventArgs e)
{
this.dataGrid1.DataSource = SomeDataTable();
AddCellFormattingColumnStyles(this.dataGrid1, new FormatCellEventHandler(FormatGridCells));
}
public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e);
public class DataGridFormatCellEventArgs : EventArgs
{
private int _column;
private int _row;
private Font _font;
private Brush _backBrush;
private Brush _foreBrush;
private bool _useBaseClassDrawing;
public DataGridFormatCellEventArgs(int row, int col, Font font1, Brush backBrush, Brush foreBrush)
{
_row = row;
_column = col;
_font = font1;
_backBrush = backBrush;
_foreBrush = foreBrush;
_useBaseClassDrawing = false;
}
public int Column
{
get{ return _column;}
set{ _column = value;}
}
public int Row
{
get{ return _row;}
set{ _row = value;}
}
public Font TextFont
{
get{ return _font;}
set{ _font = value;}
}
public Brush BackBrush
{
get{ return _backBrush;}
set{ _backBrush = value;}
}
public Brush ForeBrush
{
get{ return _foreBrush;}
set{ _foreBrush = value;}
}
public bool UseBaseClassDrawing
{
get{ return _useBaseClassDrawing;}
set{ _useBaseClassDrawing = value;}
}
}
public class DataGridFormattableTextBoxColumn : DataGridTextBoxColumn
{
//in your handler, set the EnableValue to true or false, depending upon the row & col
public event FormatCellEventHandler SetCellFormat;
private int _col;
public DataGridFormattableTextBoxColumn(int col)
{
_col = col;
}
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush);
if(SetCellFormat != null)
{
SetCellFormat(this, e);
}
if(e.UseBaseClassDrawing)
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
else
{
g.FillRectangle(e.BackBrush, bounds);
g.DrawString(this.GetColumnValueAtRow(source, rowNum).ToString(), e.TextFont, e.ForeBrush, bounds.X, bounds.Y);
}
if(e.TextFont != this.DataGridTableStyle.DataGrid.Font)
e.TextFont.Dispose();
}
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//comment to make cells unable to become editable
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}
}
}
}
只需要改变FormatGridCells中的行就行了
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace DataGridCellFormatting
{
/// <summary>
/// Form2 的摘要说明。
/// </summary>
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form2()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 56);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(536, 296);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(560, 389);
this.Controls.Add(this.dataGrid1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void FormatGridCells(object sender, DataGridFormatCellEventArgs e)
{
//color row 1 red
if(e.Row == 0)
e.BackBrush = Brushes.Red;
if(e.Row == 1)
e.BackBrush = Brushes.Red;
if(e.Row == 2)
e.BackBrush = Brushes.Red;
if(e.Row == 3)
e.BackBrush = Brushes.Red;
//color column 4 blue
// if(e.Column == 4)
// e.BackBrush = Brushes.Blue;
//
// //set font of some cells to bold
// if( (e.Row + e.Column) % 5 == 0 )
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold);
//
// //set textcolor of some cells to blue
// if( (e.Row + e.Column) % 8 == 0 )
// e.ForeBrush = Brushes.DodgerBlue;
//
// //set font of some cells to bold, underline, italic with white text on green background
// if( (e.Row + e.Column) % 9 == 0 )
// {
// e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);
// e.ForeBrush = Brushes.White;
// e.BackBrush = Brushes.Green;
// }
}
private DataTable SomeDataTable()
{
DataTable dt = new DataTable("MyTable");
//add some columns
int nCols = 10;
for(int j = 0; j < nCols; ++j)
dt.Columns.Add(new DataColumn(string.Format("col{0}", j), typeof(string)));
//add some rows
int nRows = 40;
for(int i = 0; i < nRows; ++i)
{
DataRow dr = dt.NewRow();
for(int j = 0; j < nCols; ++j)
dr[j] = string.Format("row {0} col {1}", i, j);
dt.Rows.Add(dr);
}
dt.DefaultView.AllowNew = false;//turn off append row
return dt;
}
private void AddCellFormattingColumnStyles(DataGrid grid, FormatCellEventHandler handler)
{
DataGridTableStyle ts = new DataGridTableStyle();
DataTable dt = (DataTable) grid.DataSource;
ts.MappingName = dt.TableName;
for(int j = 0; j < dt.Columns.Count; ++j)
{
DataGridFormattableTextBoxColumn cs = new DataGridFormattableTextBoxColumn(j);
cs.MappingName = dt.Columns[j].ColumnName;
cs.HeaderText = dt.Columns[j].ColumnName;
cs.SetCellFormat += handler;
ts.GridColumnStyles.Add(cs);
}
grid.TableStyles.Clear();
grid.TableStyles.Add(ts);
}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
}
private void Form2_Load(object sender, System.EventArgs e)
{
this.dataGrid1.DataSource = SomeDataTable();
AddCellFormattingColumnStyles(this.dataGrid1, new FormatCellEventHandler(FormatGridCells));
}
public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e);
public class DataGridFormatCellEventArgs : EventArgs
{
private int _column;
private int _row;
private Font _font;
private Brush _backBrush;
private Brush _foreBrush;
private bool _useBaseClassDrawing;
public DataGridFormatCellEventArgs(int row, int col, Font font1, Brush backBrush, Brush foreBrush)
{
_row = row;
_column = col;
_font = font1;
_backBrush = backBrush;
_foreBrush = foreBrush;
_useBaseClassDrawing = false;
}
public int Column
{
get{ return _column;}
set{ _column = value;}
}
public int Row
{
get{ return _row;}
set{ _row = value;}
}
public Font TextFont
{
get{ return _font;}
set{ _font = value;}
}
public Brush BackBrush
{
get{ return _backBrush;}
set{ _backBrush = value;}
}
public Brush ForeBrush
{
get{ return _foreBrush;}
set{ _foreBrush = value;}
}
public bool UseBaseClassDrawing
{
get{ return _useBaseClassDrawing;}
set{ _useBaseClassDrawing = value;}
}
}
public class DataGridFormattableTextBoxColumn : DataGridTextBoxColumn
{
//in your handler, set the EnableValue to true or false, depending upon the row & col
public event FormatCellEventHandler SetCellFormat;
private int _col;
public DataGridFormattableTextBoxColumn(int col)
{
_col = col;
}
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush);
if(SetCellFormat != null)
{
SetCellFormat(this, e);
}
if(e.UseBaseClassDrawing)
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
else
{
g.FillRectangle(e.BackBrush, bounds);
g.DrawString(this.GetColumnValueAtRow(source, rowNum).ToString(), e.TextFont, e.ForeBrush, bounds.X, bounds.Y);
}
if(e.TextFont != this.DataGridTableStyle.DataGrid.Font)
e.TextFont.Dispose();
}
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//comment to make cells unable to become editable
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}
}
}
}
只需要改变FormatGridCells中的行就行了
#2
我up
#3
o,yeah ,也太详细了吧,不错!
#4
也可以直接设置页面文件:
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 296px" runat="server" Height="104px" Width="713px" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" AllowPaging="True" PageSize="3" AutoGenerateColumns="False">
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999">
</SelectedItemStyle>
<ItemStyle ForeColor="#000066"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="userid" DataNavigateUrlFormatString="" DataTextField="userid" SortExpression="userid" HeaderText="用户ID">
</asp:HyperLinkColumn>
<asp:BoundColumn DataField="name" HeaderText="名称">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="gender" HeaderText="性别">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="email" HeaderText="EMAIL">
<HeaderStyle Width="35%"></HeaderStyle>
</asp:BoundColumn>
</Columns>
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 296px" runat="server" Height="104px" Width="713px" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" AllowPaging="True" PageSize="3" AutoGenerateColumns="False">
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999">
</SelectedItemStyle>
<ItemStyle ForeColor="#000066"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="userid" DataNavigateUrlFormatString="" DataTextField="userid" SortExpression="userid" HeaderText="用户ID">
</asp:HyperLinkColumn>
<asp:BoundColumn DataField="name" HeaderText="名称">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="gender" HeaderText="性别">
<HeaderStyle Width="20%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="email" HeaderText="EMAIL">
<HeaderStyle Width="35%"></HeaderStyle>
</asp:BoundColumn>
</Columns>
#5
因为我最近转.NET就碰到这样的需求,我研究了一下,基本可以满足要求,希望对各位有所帮助,
楼主记得给分啊
楼主记得给分啊
#6
顶,接点分^_^
无聊就接分来了
无聊就接分来了
#7
OK,寫的非常好.无聊來了.
#8
我晕!
tkx222(tkx) !!这个问题有必要回答的这么详细不?
唉! 接分狂!!
太想分了吧
tkx222(tkx) !!这个问题有必要回答的这么详细不?
唉! 接分狂!!
太想分了吧
#9
看得狂晕,呵呵。支持热情!
#10
我支持一楼的兄弟,只有这样才好
#11
利用DataGrid的ItemStyle样式
<asp:DataGrid
ID="..."
ItemStyle-BackColor="Blue"
ItemStyle-Color="Red"
Runat="Server"/>
...
<asp:DataGrid
ID="..."
ItemStyle-BackColor="Blue"
ItemStyle-Color="Red"
Runat="Server"/>
...
#12
我下面有一個例子,希望對你有幫助...
datagrid 的樣式表(DataGridTableStyle)應用...
首先 我們先定一個 datatable 和 一個datarow
Private idtb_temp As New DataTable
Private idrw_row As DataRow
private sub GetDataTable()
idtb_temp.Columns.Add("prdodr_subodr_code") '''定義datatable 的列名
idtb_temp.TableName = "SearchTable"
Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn
Dim ldgts_styles As New Windows.Forms.DataGridTableStyle
ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow
'''選中行的前景色,即字體顏色
ldgts_styles.SelectionBackColor = System.Drawing.Color.Brown '''選中行的背景色
ldgts_styles.ForeColor = System.Drawing.Color.Coral
''' datagrid 中將要顯示的字的顏色
ldgts_styles.AlternatingBackColor = System.Drawing.Color.Cyan
'''datagrid中奇數行所顯示的顏色
ldgts_styles.BackColor = System.Drawing.Color.Cyan
'''datagrid中偶數行所顯示的顏色
ldgts_styles.AllowSorting = False
'''些樣式表定義datagrid不允許自動排序..
ldgts_styles.MappingName = "SearchTable"
ldcl_header = New Windows.Forms.DataGridTextBoxColumn
'''實例化一個datagridtextboxcolumn
ldcl_header.MappingName = "prdodr_subodr_code"
'''引用前面定義的 “列名”
ldcl_header.HeaderText = "第一列"
'''datagrid 中顯示的 表列頭 文字
ldcl_header.ReadOnly = True '''些列設定為只讀
ldcl_header.TextBox.BorderStyle = BorderStyle.Fixed3D
ldcl_header.TextBox.ForeColor = System.Drawing.Color.Red
ldgts_styles.GridColumnStyles.Add(ldcl_header)
For i As Integer = 0 To 7
idrw_row = idtb_temp.NewRow
idrw_row.Item("prdodr_subodr_code") = "第" & i & "行"
idtb_temp.Rows.Add(idrw_row)
Next
idtb_temp.DefaultView.AllowNew = False
Me.DataGrid1.TableStyles.Add(ldgts_styles)
Me.DataGrid1.DataSource = idtb_temp
end sub
datagrid 的樣式表(DataGridTableStyle)應用...
首先 我們先定一個 datatable 和 一個datarow
Private idtb_temp As New DataTable
Private idrw_row As DataRow
private sub GetDataTable()
idtb_temp.Columns.Add("prdodr_subodr_code") '''定義datatable 的列名
idtb_temp.TableName = "SearchTable"
Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn
Dim ldgts_styles As New Windows.Forms.DataGridTableStyle
ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow
'''選中行的前景色,即字體顏色
ldgts_styles.SelectionBackColor = System.Drawing.Color.Brown '''選中行的背景色
ldgts_styles.ForeColor = System.Drawing.Color.Coral
''' datagrid 中將要顯示的字的顏色
ldgts_styles.AlternatingBackColor = System.Drawing.Color.Cyan
'''datagrid中奇數行所顯示的顏色
ldgts_styles.BackColor = System.Drawing.Color.Cyan
'''datagrid中偶數行所顯示的顏色
ldgts_styles.AllowSorting = False
'''些樣式表定義datagrid不允許自動排序..
ldgts_styles.MappingName = "SearchTable"
ldcl_header = New Windows.Forms.DataGridTextBoxColumn
'''實例化一個datagridtextboxcolumn
ldcl_header.MappingName = "prdodr_subodr_code"
'''引用前面定義的 “列名”
ldcl_header.HeaderText = "第一列"
'''datagrid 中顯示的 表列頭 文字
ldcl_header.ReadOnly = True '''些列設定為只讀
ldcl_header.TextBox.BorderStyle = BorderStyle.Fixed3D
ldcl_header.TextBox.ForeColor = System.Drawing.Color.Red
ldgts_styles.GridColumnStyles.Add(ldcl_header)
For i As Integer = 0 To 7
idrw_row = idtb_temp.NewRow
idrw_row.Item("prdodr_subodr_code") = "第" & i & "行"
idtb_temp.Rows.Add(idrw_row)
Next
idtb_temp.DefaultView.AllowNew = False
Me.DataGrid1.TableStyles.Add(ldgts_styles)
Me.DataGrid1.DataSource = idtb_temp
end sub
#13
tkx222(tkx)
好好好!!!
好好好!!!
#14
支持tkx222(tkx)
#15
TO:tkx222(tkx)
这段代码有个问题,我排序之后原有的数据顺序变了,而颜色还是在前面几行,这是不是有点不符合?
这段代码有个问题,我排序之后原有的数据顺序变了,而颜色还是在前面几行,这是不是有点不符合?
#16
支持一楼的师傅,有时间教教我