0

我有一个数据库表(名为 PatientDetails),其中包括以下列:

PatientId not null,
title,
sex,
lastname,
birthday,
firstname,
middlename,
remarkline,
remarks

通过使用上表,我想在 c# 中将PatientIdasParent和 childnode 作为firstnamea TreeView。我怎样才能做到这一点 ?

我做了一些代码隐藏如下:

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = RunQuery("select PatientId,firstname from PatientDetails");

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        TreeNode root = new TreeNode(
            ds.Tables[0].Rows[i][1].ToString(),
            ds.Tables[0].Rows[i][0].ToString());

        root.SelectAction = TreeNodeSelectAction.Expand;
        CreateNode(root);
        TVPatArc.Nodes.Add(root);
    }      
}

void CreateNode(TreeNode node)
{
    DataSet ds = RunQuery("Select PatientId,firstname "
                          + "from PatientDetails where PatientId ="
                          + node.Value);

    if (ds.Tables[0].Rows.Count == 0)
    {
        return;
    }

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        TreeNode tnode = new TreeNode(
            ds.Tables[0].Rows[i][1].ToString(),
            ds.Tables[0].Rows[i][0].ToString());

        tnode.SelectAction = TreeNodeSelectAction.Expand;
        node.ChildNodes.Add(tnode);
        CreateNode(tnode);
    }
}

DataSet RunQuery(String Query)
{
    DataSet ds = new DataSet();
    String connStr = "Data Source=LOCALHOST\\SQLEXPRESS;"
                     + "Initial Catalog=MyDatabase;"
                     + "User ID=sa;Password=sa";

    using (SqlConnection conn = new SqlConnection(connStr))
    {
        SqlCommand objCommand = new SqlCommand(Query, conn);
        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        da.Fill(ds);
        da.Dispose();
    }

    return ds;
}

但是CreateNode(tnode);它给出了System.StackOverflowException. 我认为这是由于无限循环。但我不确定。

4

2 回答 2

1

为什么你需要多次点击 DB?如果您从同一记录构造父子节点?

在页面加载尝试这样

DataSet ds = RunQuery("select PatientId,firstname from PatientDetails");

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode root = new TreeNode(ds.Tables[0].Rows[i]["ID"].ToString(), ds.Tables[0].Rows[i]["ID"].ToString());
root.SelectAction = TreeNodeSelectAction.Expand;
TreeNode child = new TreeNode(ds.Tables[0].Rows[i]["ID"].ToString(), ds.Tables[0].Rows[i]["FirstName"].ToString());
root.ChildNodes.Add(child);
TVPatArc.Nodes.Add(root);
}
于 2013-10-01T10:08:12.693 回答
0

如果您查看您的查询,您将检索到相同的患者广告:

RunQuery("从 PatientDetails 中选择 PatientId,firstname 其中 PatientId =" + node.Value);

我建议更改查询以按其父项检索患者,如果数据库中的字段是 ParentPatientId,则使用:

RunQuery("Select PatientId,firstname from PatientDetails where ParentPatientId =" + node.Value);

顺便说一句,这是非常低效的,因为您将为每位患者启动至少一个查询,如果您有一百万个患者,那么您将启动至少一百万个查询。最好在一个查询中检索所有内容,按 ParentPatientId 排序,然后根据结果构建树。如果您使用的是 Oracle,您还可以使用 DML 命令来帮助您构建树(CONNECT BY 和 START WITH)。

于 2013-10-01T10:06:50.880 回答