在C#中,使用DataGridView控件能很方便的显示从数据库中检索的数据.
1.首先,连接数据库
using (sqlConnection cnn = new SqlConnection(strConn)) { try { cnn.Open(); bConn = true; } catch (Exception exp) { MessageBox.Show(exp.Message); bConn = false; } } }
2.构造SQL语句去数据库查询,并奖结果放到DataGridView控件
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的样式进行设置
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; } }
|
请发表评论