如何循环数据集中的特定行并设置为treeview

时间:2013-10-11 10:23:21

标签: c# asp.net

我想遍历每个数据行并检查pid的值,直到它获得0或null或空值...下面是我的代码

if (!string.IsNullOrEmpty(pIDstr))
{
    int patientID = Convert.ToInt32(pID);

    //string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
    string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
    string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
    using(SqlConnection conn = new SqlConnection(connection))
    {
        //SqlConnection conn = new SqlConnection(con);
        DataSet ds;
        ds = new DataSet();
        SqlDataAdapter cmpatientexam;
        conn.Open();

        cmpatientexam = new SqlDataAdapter(sqlquery, conn);
        cmpatientexam.Fill(ds, "PatientExam");

        foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
        {

                TreeNode tvpatexam = new TreeNode();
                tvpatexam.Text = patrow["PId"].ToString();
                TreeView1.Nodes.Add(tvpatexam);

                for //loop for checking all the patrow["PId"] value
                {
                    TreeNode childtvpatexam = new TreeNode();
                    childtvpatexam.Text = patrow["Exam"].ToString();
                    tvpatexam.ChildNodes.Add(childtvpatexam);
                }
            //TreeView1.Nodes.Add(tvpatexam);
        }


        ds.Dispose();
        cmpatientexam.Dispose();
        conn.Close();
        conn.Dispose();
    }
}

如果有可能,任何人都可以发送代码......非常感谢

我的数据库表PatExam包含以下值

PId     Exam
1004    firstexam
1004    secondexam
1004    thridexam
1004    fourthexam

所以我希望1004作为我的父节点,并将所有考试值1004作为树视图中的子节点....

怎么可能?

1 个答案:

答案 0 :(得分:1)

要为每个父节点添加子节点,请尝试以下

TreeNode pidNode = new TreeNode();
pidNode.Text = PIDstr;

foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
{
    TreeNode examType = new TreeNode();
    examType.Text = patrow["Exam"].ToString();
    pidNode.Nodes.Add(examType);
}

TreeView1.Nodes.add(pidNode);

无需检查Null0值 - 不确定您的要求。

<强>更新

如果重复添加节点;这意味着用于生成节点列表的动作是重复的。您可以使用TreeView1.Nodes.Clear()删除所有节点,也可以检查特定节点是否存在。

要删除所有节点,请尝试

TreeView1.Nodes.Clear();

要删除特定节点并刷新其内容,请尝试重新填充节点之前的操作。

TreeNode node = TreeView1.Nodes.FirstOrDefault(p=>p.Text == PIDstr);
TreeView1.Nodes.Remove(node);