首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

更改DataGrid行的颜色解决方法

2012-01-09 
更改DataGrid行的颜色根据行的字段值来更改DataGrid行的颜色,[解决办法]給你兩段代碼,地址不記得了在dataG

更改DataGrid行的颜色
根据行的字段值来更改DataGrid行的颜色,

[解决办法]
給你兩段代碼,地址不記得了
在dataGrid 中如何设置行的颜色:
namespace DataGridRowHeaderText
{
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

public class Form1 : System.Windows.Forms.Form
{
private DataGridRowHeaderText.MyDataGrid dataGrid1;
private Point pointInCell00;

private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code

private void InitializeComponent()
{
this.dataGrid1 = new DataGridRowHeaderText.MyDataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.dataGrid1.DataMember = " ";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(24, 24);
this.dataGrid1.Name = "dataGrid1 ";
this.dataGrid1.Size = new System.Drawing.Size(576, 248);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Paint += new System.Windows.Forms.PaintEventHandler(this.dataGrid1_Paint);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(624, 301);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.dataGrid1});
this.Name = "Form1 ";
this.Text = "Form1 ";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);

}
#endregion

[STAThread]
public static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{
// Set the connection and sql strings
// assumes your mdb file is in your root
string connString = "Initial Catalog=Northwind;Data Source=.;user id=sa ;password=; ";
string sqlString = "SELECT * FROM orders ";

SqlDataAdapter dataAdapter = null;
DataSet _dataSet = null;

try
{
// Connection object
SqlConnection connection = new SqlConnection(connString);

// Create data adapter object
dataAdapter = new SqlDataAdapter(sqlString, connection);

// Create a dataset object and fill with data using data adapter 's Fill method
_dataSet = new DataSet();
dataAdapter.Fill(_dataSet, "orders ");
connection.Close();


}
catch(Exception ex)
{
MessageBox.Show( "Problem with DB access-\n\n connection: "
+ connString + "\r\n\r\n query: " + sqlString
+ "\r\n\r\n\r\n " + ex.ToString());
this.Close();
return;
}
////if you want to use a tablestyle, uncomment this block....
//// Create a table style that will hold the new column style
//// that we set and also tie it to our customer 's table from our DB
//DataGridTableStyle tableStyle = new DataGridTableStyle();
//tableStyle.MappingName = "orders ";
//
//
//// since the dataset has things like field name and number of columns,
//// we will use those to create new columnstyles for the columns in our DB table
//int numCols = _dataSet.Tables[ "orders "].Columns.Count;
//DataGridTextBoxColumn aColumnTextColumn ;
//for(int i = 0; i < numCols; ++i)
//{
//aColumnTextColumn = new DataGridTextBoxColumn();
//aColumnTextColumn.HeaderText = _dataSet.Tables[ "orders "].Columns[i].ColumnName;
//
////set col 3 format to a time only
//if(i == 3)
//aColumnTextColumn.Format = "mm:ss t ";// "MM/dd/yyyy ";
//
//aColumnTextColumn.MappingName = _dataSet.Tables[ "orders "].Columns[i].ColumnName;
//tableStyle.GridColumnStyles.Add(aColumnTextColumn);
//}
//
//// make the dataGrid use our new tablestyle and bind it to our table
//dataGrid1.TableStyles.Clear();
//tableStyle.AlternatingBackColor = Color.Firebrick;
//
//dataGrid1.TableStyles.Add(tableStyle);

dataGrid1.DataSource = _dataSet.Tables[ "orders "];//.DefaultView;

//set the header width to something apporpriate
//this.dataGrid1.TableStyles[ "orders "].RowHeaderWidth = 50; //use if tablestyle
this.dataGrid1.RowHeaderWidth = 50; //use if no tablestyle


//set topleft corner point so we can locate the toprow
//pointInCell00 = new Point(dataGrid1.GetCellBounds(0,0).X + 4, dataGrid1.GetCellBounds(0,0).Y + 4);
pointInCell00 = new Point(dataGrid1.GetCellBounds(0,0).X + 4, dataGrid1.GetCellBounds(0,0).Y + 4);

}

private void dataGrid1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
int row = TopRow();
int yDelta = dataGrid1.GetCellBounds(row, 0).Height + 1;
int y = dataGrid1.GetCellBounds(row, 0).Top + 2;

CurrencyManager cm = (CurrencyManager) this.BindingContext[dataGrid1.DataSource, dataGrid1.DataMember];

while(y < dataGrid1.Height - yDelta && row < cm.Count)
{
//get & draw the header text...
//string text = string.Format( "row{0} ", row);
string text = string.Format( "{0} ", row);
e.Graphics.DrawString(text, dataGrid1.Font, new SolidBrush(Color.Black), 10, y);
y += yDelta;
row++;
}
}

public int TopRow()
{
DataGrid.HitTestInfo hti = dataGrid1.HitTest(this.pointInCell00);
return hti.Row;
}
}

public class MyDataGrid : DataGrid
{
protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
{
DataGrid.HitTestInfo hti = this.HitTest(new Point(e.X, e.Y));
if(hti.Type == DataGrid.HitTestType.RowResize)
{
return; //no baseclass call
}
base.OnMouseMove(e);
}
}
}
------解决方案--------------------


//-------- 代码(2)-------------
/*-------------------------------
* 本文有TheAres(班门斧)写成,axe@qingdaonews.com. 请保留著作权
*
* 引用者请注意:
* 1)代码随意散发和使用,请保留作者信息. _par * 2)对于有代码引发的灾难,本人不负责任何责任.
*/

using System;
using System.Drawing;
using System.Drawing.Drawing2D; _par using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
usingSystem.Data.SqlClient;
//using System.Data.OleDb; _par
namespace TheAresDataGrid
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
private System.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();

}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer `generated code
private void InitializeComponent()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout()&#128;u32 ?
//
// dataGrid1
//
this.dataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.dataGrid1.DataMember = " ";
this.dataGrid1.HeaderForeColor =_u32 ? System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(24, 24);
this.dataGrid1.Name = "dataGrid1 ";
this.dataGrid1.Size = new System.Drawing.Size(448, 280);
this.dataGrid1.TabIndex = 0; _par //
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(504, 341);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.dataGrid1});
this.Name = "Form1 ";
this.Text = "Form1 ";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point . for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs _u32 ?e)
{
string connString = "Initial Catalog=Northwind;Data Source=.;user id=sa ;password=; ";
string sqlString = "SELECT *_u32 ? FROM customers ";

SqlDataAdapter dataAdapter = null;
DataSet _dataSet = null;

try
{ SqlConnection connection=new SqlConnection(connString);
connection.Open();
dataAdapter = new SqlDataAdapter(sqlString, _u99 ?onnection);



_dataSet = new DataSet();
dataAdapter.Fill(_dataSet,_u32 ? "customers ");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show( "Problem _u119 ?ith DB access-\n\n connection: "
+ connString + "\r\n\r\n query: " + sqlString
+ "\r\n\r\n\r\n " + ex.ToString());
this.Close();
return;
}

DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = _u32 ? "customers ";

int numCols = _dataSet.Tables[ "customers "].Columns.Count;
DataGridEnableTextBoxColumn_u32 ? aColumnTextColumn ;
for(int i = 0; i < numCols; ++i)
{
aColumnTextColumn = new DataGridEnableTextBoxColumn(i);

aColumnTextColumn.HeaderText = _dataSet.Tables[ "customers "].Columns[i].ColumnName;
aColumnTextColumn.MappingName = _dataSet.Tables[ "customers "].Columns[i].ColumnName;
aColumnTextColumn.CheckCellEnabled += new DataGridEnableTextBoxColumn.EnableCellEventHandler(SetEnableValues);

tableStyle.GridColumnStyles.Add(aColumnTextColumn);
}

dataGrid1.TableStyles.Clear();
dataGrid1.TableStyles.Add(tableStyle);
dataGrid1.DataSource = _dataSet.Tables[ "customers "];
}

public void SetEnableValues(object sender,DataGridEnableEventArgs e)
{
e.BackColor = Color.White;
if (this.dataGrid1[e.Row,8].ToString()_u32 ? == "Mexico ")
{
e.BackColor = Color.Green;
}
}
}
}
//-------- 代码(2)结束-------------

热点排行