在C#中,使用DataGridView控件能很方便的显示从数据库中检索的数据.
1.首先,连接数据库
public void Connect()
{
string strConn = string.Format("Data Source = IP;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DataBaseName;User ID = UserID;");
using (sqlConnection cnn = new SqlConnection(strConn))
{
try
{
cnn.Open();
bConn = true;
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
bConn = false;
}
}
}
2.构造SQL语句去数据库查询,并奖结果放到DataGridView控件
string strSql = string.Format("select * from TableName where ID < 50 order by ID");
DataSet dataset = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter(strSql, cnn);
myDataAdapter.Fill(dataset); //这句跟下面的顺序不能颠倒
dataGridView1.DataSource = dataset.Tables[0];//填充
3.添加DataGridView控件的右键菜单
//在CellMouseClick里操作
private void DataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= 0)
{
dataGridView1.ClearSelection();
dataGridView1.Rows[e.RowIndex].Selected = true; //选中
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];//选中单元
DataGridRightMenu.Show(MousePosition.X, MousePosition.Y); //在点击处显示右键菜单
}
}
}
4.对DataGridView的样式进行设置
//设置可以根据自己需要来进行
//设置列宽
dataGridView1.Columns[0].FillWeight = 8;
dataGridView1.Columns[1].FillWeight = 15;
dataGridView1.Columns[2].FillWeight = 15;
dataGridView1.Columns[3].FillWeight = 8;
dataGridView1.Columns[4].FillWeight = 50;
dataGridView1.Columns[5].FillWeight = 4;
//设置标题文字
dataGridView1.Columns[0].HeaderText = "A";
dataGridView1.Columns[1].HeaderText = "B";
dataGridView1.Columns[2].HeaderText = "C";
dataGridView1.Columns[3].HeaderText = "D";
dataGridView1.Columns[4].HeaderText = "E";
dataGridView1.Columns[5].HeaderText = "F";
5.设置显示时候相隔颜色
//颜色设置,相隔行颜色不同
public void SetDataGridColor(int nCount)
{
for (int i = 0; i < this.dataGridView1.Rows.Count; )
{
this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
i += 2;
}
}