很多數(shù)據(jù)都有父節(jié)點與子節(jié)點,我們希望單擊父節(jié)點的時候可以展開父節(jié)點下的子節(jié)點數(shù)據(jù)。
比如一個醫(yī)院科室表,有父科室與子科室,點擊父科室后,在父科室下面可以展現(xiàn)該科室下的所有子科室。
我們來說一下在DataGridView中如何實現(xiàn)這個功能。
首先,創(chuàng)建示例數(shù)據(jù):
示例數(shù)據(jù)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醫(yī)院') insert into Department values('門診內科',1,'2222','XXX醫(yī)院') insert into Department values('門診手術',1,'3333','XXX醫(yī)院') insert into Department values('門診兒科',1,'4444','XXX醫(yī)院') insert into Department values('神經內室',2,'5555','XXX醫(yī)院') insert into Department values('神經外科',2,'6666','XXX醫(yī)院') insert into Department values('住院手術',2,'7777','XXX醫(yī)院') insert into Department values('住院康復',2,'8888','XXX醫(yī)院') 其實思路很簡單,就是在展開父節(jié)點的時候,在父節(jié)點下插入新的DataGridViewRow;收縮父節(jié)點的時候,在父節(jié)點下刪除該子節(jié)點的DataGridViewRow。
為了簡便,代碼中的數(shù)據(jù)讀取我都直接硬編碼了。
加載父節(jié)點數(shù)據(jù),除了數(shù)據(jù)庫中的列外我還新加了兩列: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的單擊事件了,分別在事件中寫展開的插入與收縮的刪除.
插入子節(jié)點:
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"]; } } //將IsEx設置為true,標明該節(jié)點已經展開 this.dataGridView1.Rows[e.RowIndex].Cells["IsEx"].Value = "true"; this.dataGridView1.Rows[e.RowIndex].Cells["EX"].Value = "-";
新聞熱點
疑難解答
圖片精選