datagridview树状显示
将dataGridView的数据分级显示,其结果就像树状显示。
不能显示图片,就和有多列的树显示一样。
我们科目管理为例:
程序主要的逻辑思路如下:
1、当前行有+号显示明细科目:A:明细中有+号。B:明细中没有+号。
2、当前行没有+号收缩显示:A:明细中有+号。B:明细中没有+号。
Private void dataGridView1_CellDoubleClick(object sender,DataGridViewCellEventArgs e)
{
String aa = Convert.ToString(dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value).Trim();
//当前行有+号,显示明细
if (aa.StartsWith("+"))
{
aa = aa.Substring(1, aa.Length-1);
int currow = dataGridView1.CurrentCell.RowIndex;
for (int i = currow; i < dataGridView1.Rows.Count; i++)
{
string ccc = dataGridView1[0, i].Value.ToString().Trim();
//如果明细中有+号,处理方法
if (ccc.Trim().StartsWith("+"))
{
ccc = ccc.Substring(1, ccc.Length - 1);
if (ccc.Length > aa.Length)
{
string ttt = ccc.Substring(0, aa.Length);
if (ttt == aa)
{
dataGridView1.Rows[i].Visible = true;
//dataGridView1[0, i].Value = ccc;
//按级别显示
string abcd = "";
for (int k = 2; k <= Convert.ToInt32(dataGridView1[4, i].Value.ToString()); k++)
{
abcd += " ";
}
dataGridView1[0, i].Value = abcd + ccc;
}
}
}
//如果明细中没有+号,处理方法。
else
{
if (dataGridView1[0, i].Value.ToString().Trim().Length > aa.Length)
{
string ttt = dataGridView1[0, i].Value.ToString().Trim().Substring(0, aa.Length);
if (ttt == aa)
{
dataGridView1.Rows[i].Visible = true;
dataGridView1[0, currow].Value = aa;
//按级别显示
string abcd ="";
for (int k = 2; k <= Convert.ToInt32(dataGridView1[4, currow].Value.ToString()); k++)
{
abcd +=" ";
}
dataGridView1[0, currow].Value = abcd + aa;
}
}
}
}
}
//当前行没有+号,合并显示
else
{
int currow = dataGridView1.CurrentCell.RowIndex;
for (int i = currow; i < dataGridView1.Rows.Count; i++)
{
string ccc = dataGridView1[0, i].Value.ToString().Trim();
//如果明细中有+号,处理方法
if (ccc.Trim().StartsWith("+"))
{
ccc = ccc.Substring(1, ccc.Length-1);
if (ccc.Length > aa.Length)
{
string ttt = ccc.Substring(0, aa.Length);
if (ttt == aa)
{
dataGridView1.Rows[i].Visible = false;
//按级别显示
string abcd = "";
for (int k = 2; k <= Convert.ToInt32(dataGridView1[4, currow].Value.ToString()); k++)
{
abcd += " ";
}
dataGridView1[0, currow].Value =abcd+dataGridView1[0, currow].Value.ToString();
}
}
}
//如果明细中没有+号,处理方法。
else
{
if (dataGridView1[0, i].Value.ToString().Trim().Length > aa.Length)
{
string ttt = dataGridView1[0, i].Value.ToString().Trim().Substring(0, aa.Length);
if (ttt == aa)
{
dataGridView1.Rows[i].Visible = false;
if (dataGridView1[0, currow].Value.ToString().Trim().StartsWith("+"))
dataGridView1[0, currow].Value =dataGridView1[0, currow].Value.ToString().Trim();
else
dataGridView1[0, currow].Value = "+" + dataGridView1[0, currow].Value.ToString().Trim();
//按级别显示
string abcd = "";
for (int k = 2; k <= Convert.ToInt32(dataGridView1[4, currow].Value.ToString()); k++)
{
abcd += " ";
}
dataGridView1[0, currow].Value=abcd+dataGridView1[0, currow].Value.ToString();
}
}
}
}
}
}