如果该dataGridView是跟数据库绑定的,则可以触发DataBindingComplete事件:
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (this.dataGridView1.Rows.Count != 0)
{
for (int i = 0; i < this.dataGridView1.Rows.Count; )
{
this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
i += 2;
}
}
}
如果没有绑定数据库,那么当dataGridView中的数据有所改变或显示的时候可以添加以下的代码:
if (this.dataGridView1.Rows.Count != 0)
{
for (int i = 0; i < this.dataGridView1.Rows.Count; )
{
this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
i += 2;
}
}
Color color = ((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor;
if (((DataGridView)sender).Rows[e.RowIndex].Selected)
color = ((DataGridView)sender).RowHeadersDefaultCellStyle.SelectionForeColor;
else
color = ((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor;
using (SolidBrush b = new SolidBrush(color))
{
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 6);
}
最近做了一个DataGridView的分页显示Demo。也是看见网络上很多人询问关于DataGridView如何做分页。根据我的认识,Visual Sutido 2005里的DataGridView控件是没有带分页属性的,因此咱们必须通过写代码去实现分页功能。
好了,先看一下Demo的界面。
从界面可以看到,在设计时需要一个DataGridView、BindingNavigate、BindingSource控件,分别命名为dgvInfo、bdnInfo、bdsInfo。
在bdnInfo控件中添加几个用于选择页面的lable和botton,如上图所示。
设计时:
1、定义几个所需的公有成员:








2、在窗体载入事件中,从数据源读取记录到DataTable中:
string strConn = "SERVER=127.0.0.1;DATABASE=NORTHWIND;UID=SA;PWD=ULTRATEL"; //数据库连接字符串
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string strSql = "SELECT * FROM CUSTOMERS";
SqlDataAdapter sda = new SqlDataAdapter(strSql,conn);
sda.Fill(ds,"ds");
conn.Close();
dtInfo = ds.Tables[0];
InitDataSet();
3、用当前页面数据填充DataGridView









































4、菜单响应事件:



































