关于gridview

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
int pageSize = 0; //每页显示行数
int nMax = 0; //总记录数
int pageCount = 0; //页数=总记录数/每页显示行数
int pageCurrent = 0; //当前页号

DataTable dt = new DataTable();

private SqlDataAdapter dataAdapter = new SqlDataAdapter();

public Form2()
{
InitializeComponent();
GetData("Select * from GpsLog");
}


//从数据库去数据
private void GetData(String str)
{

String connectionString = "server=192.168.69.9;uid=sa;pwd=gpsdbsa;database=gpsdb2";
dataAdapter = new SqlDataAdapter(str, connectionString);
SqlCommandBuilder sqlcom = new SqlCommandBuilder(dataAdapter);

dataAdapter.Fill(dt);
InitData();

}

//行背景颜色显示

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.Green;
i += 2;
}
}
}

//显示行号
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
string title = (e.RowIndex + (pageCurrent - 1) * 20 +1).ToString();
Brush bru = Brushes.Black;
e.Graphics.DrawString(title, dataGridView1.RowHeadersDefaultCellStyle.Font,
bru, e.RowBounds.Location.X + dataGridView1.RowHeadersWidth / 2 - 4, e.RowBounds.Location.Y + 4);
}


private void InitData()
{
pageSize = 20; //设置页面行数
nMax = dt.Rows.Count;

pageCount = (nMax / pageSize); //计算出总页数

if ((nMax % pageSize) > 0) pageCount++;

pageCurrent = 1; //当前页数从1开始

LoadData();
}


//分页设计,每页显示20行
private void LoadData()
{
int nStartPos = 0; //当前页面开始记录行
int nEndPos = 0; //当前页面结束记录行

DataTable dtTemp = dt.Clone(); //克隆DataTable结构框架

if (pageCurrent == pageCount)
nEndPos = nMax;
else
nEndPos = pageSize * pageCurrent;

nStartPos = nEndPos - pageSize;

label1.Text = Convert.ToString(pageCurrent)+"/"+pageCount.ToString();

//从元数据源复制记录行
for (int i = nStartPos; i < nEndPos; i++)
{
dtTemp.ImportRow(dt.Rows[i]);

}
bindingSource1.DataSource = dtTemp;
dataGridView1.DataSource = bindingSource1;
}

private void label2_Click(object sender, EventArgs e)
{
pageCurrent--;
if (pageCurrent <= 0)
{
MessageBox.Show("当前已经是第一页!");
return;
}

LoadData();
}

private void label3_Click(object sender, EventArgs e)
{
pageCurrent++;
if (pageCurrent > pageCount)
{
MessageBox.Show("当前已经是最后一页!");
return;
}

LoadData();
}

private void label5_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入要跳转的页数!");
return;
}

int p = Convert.ToInt32(textBox1.Text);
pageCurrent = p;
LoadData();

}
}
}

posted @ 2012-08-03 18:04  刀锋浪  阅读(181)  评论(0编辑  收藏  举报