因为是三层架构,所以先在Dal层,将数据放入DataTable中先
public DataTable dataGrid(string UserName) { string sql = string.Format("SELECT * FROM demoUsers WHERE UserName=@UserName"); Class1 q = new Class1(cc); ArrayList paramlist = new ArrayList(); paramlist.Add(q.CreateParameter("@UserName", UserName, DbType.String, 50)); IDataParameter[] param = (IDataParameter[])paramlist.ToArray(typeof(IDataParameter)); return q.testDataTable(sql, param); }
所需要的实体对象,Mod都已经有了,在dataGridView任务中添加自己想要显示出来的数据,设置好后,UI代码
1 private void WorkerBasicMessage_Load(object sender, EventArgs e) 2 { 3 dataGridView1.AutoGenerateColumns = false;//不需要的数据不选 4 } 5 6 private void button1_Click(object sender, EventArgs e) 7 { 8 9 string userName; 10 SqlHelper ds = new SqlHelper(); 11 if (true) 12 { 13 userName = textBox1.Text.Trim(); 14 } 15 DataTable dt = ds.dataGrid(userName);//将Id传进去得到一个数据表 16 dataGridView1.DataSource = dt; 17 }
数据名要跟数据中对应,如下图加黑的UserId
//联表查询统计所有记录group by sql语句运用 public DataTable selectAllMessage() { string sql = string.Format("select demoUsers.TrueName,COUNT (leaveMessage.UserId)as 请假次数 from demoUsers inner join leaveMessage on demoUsers.UserId=leaveMessage.UserId group by demoUsers.TrueName"); DataConn conn = new DataConn(conStr); ArrayList paramlist = new ArrayList(); IDataParameter[] param = (IDataParameter[])paramlist.ToArray(typeof(IDataParameter)); return conn.testDataTable(sql, param); }
点击控件的记录显示详细数据的话,可设计单击事件CellClick
datagridview 索引超出范围。必须为非负值并小于集合大小
1 private void dGV1_CellClick(object sender, DataGridViewCellEventArgs e) 2 { 3 this.radioButton2.Checked = true; 4 int currentRowIndex = dGV1.CurrentCell.RowIndex; 5 if (currentRowIndex >= 0) 6 { 7 this.label6.Text = Convert.ToString(dGV1[0, currentRowIndex].Value).Trim();//显示编号 8 this.label4.Text = Convert.ToString(dGV1[1, currentRowIndex].Value).Trim();//显示标题 9 this.textBox1.Text = Convert.ToString(dGV1[3, currentRowIndex].Value).Trim();//问题描述 10 this.textBox3.Text = Convert.ToString(dGV1[5, currentRowIndex].Value).Trim();//解决方法描述 11 if (Convert.ToString(dGV1[6, currentRowIndex].Value).Trim() == "已解决") 12 { 13 this.radioButton1.Checked = true; 14 } 15 } 16 }