很多数据都有父节点与子节点,我们希望单击父节点的时候可以展开父节点下的子节点数据。
比如一个医院科室表,有父科室与子科室,点击父科室后,在父科室下面可以展现该科室下的所有子科室。
我们来说一下在DataGridView中如何实现这个功能。
首先,创建示例数据:
示例数据SQL
- create table Department
- (
- ID int identity(1,1) not null,
- DName varchar(20) null,
- DparentId int null,
- Dtelphone varchar(20) null,
- Dhospital varchar(50) null
- )
- insert into Department values('门诊外室',1,'1111','XXX医院')
- insert into Department values('门诊内科',1,'2222','XXX医院')
- insert into Department values('门诊手术',1,'3333','XXX医院')
- insert into Department values('门诊儿科',1,'4444','XXX医院')
- insert into Department values('神经内室',2,'5555','XXX医院')
- insert into Department values('神经外科',2,'6666','XXX医院')
- insert into Department values('住院手术',2,'7777','XXX医院')
- insert into Department values('住院康复',2,'8888','XXX医院')
|
其实思路很简单,就是在展开父节点的时候,在父节点下插入新的DataGridViewRow;收缩父节点的时候,在父节点下删除该子节点的DataGridViewRow。
为了简便,代码中的数据读取我都直接硬编码了。
加载父节点数据,除了数据库中的列外我还新加了两列:IsEx与EX。
- private void DataGridBing(DataTable table)
- {
- if (table.Rows.Count > 0)
- {
- for (int i = 0; i < table.Rows.Count; i++)
- {
-
- int k = this.dataGridView1.Rows.Add();
- DataGridViewRow row = this.dataGridView1.Rows[k];
- row.Cells["ID"].Value = table.Rows[i]["ID"];
- row.Cells["DName"].Value = table.Rows[i]["DName"];
- row.Cells["Daddress"].Value = table.Rows[i]["Daddress"];
- row.Cells["Dtelphone"].Value = table.Rows[i]["Dtelphone"];
-
- row.Cells["IsEx"].Value = "false";
-
- row.Cells["EX"].Value = "+";
- }
- }
- }
|
下面就是Cell的单击事件了,分别在事件中写展开的插入与收缩的删除.
插入子节点:
- string isEx=this.dataGridView1.Rows[e.RowIndex].Cells["IsEx"].Value.ToString();
- if (this.dataGridView1.Columns[e.ColumnIndex].Name == "EX" && isEx=="false")
- {
- string id = this.dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString();
- DataTable table = GetDataTable("select * from Department where DparentId="+id);
- if (table.Rows.Count > 0)
- {
-
- this.dataGridView1.Rows.Insert(e.RowIndex+1, table.Rows.Count);
- for (int i = 0; i < table.Rows.Count; i++)
- {
- DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex + i+1];
- row.DefaultCellStyle.BackColor = Color.CadetBlue;
- row.Cells["ID"].Value = table.Rows[i]["ID"];
- row.Cells["DName"].Value = table.Rows[i]["DName"];
- row.Cells["Daddress"].Value = table.Rows[i]["Daddress"];
- row.Cells["Dtelphone"].Value = table.Rows[i]["Dtelphone"];
- }
- }
-
- this.dataGridView1.Rows[e.RowIndex].Cells["IsEx"].Value = "true";
- this.dataGridView1.Rows[e.RowIndex].Cells["EX"].Value = "-";
|