昨天用ASP.NET中实现导航栏的动态添加功能。Catalog表定义了Id,ParentId,Title三个字段。
把导航栏按照级别设计成树形结构。想实现的功能是在一个下拉框中显示导航栏的树形结构。写了下面这个方法:
public void OrderTree( SqlConnection connection , int parentId )
{
string cmdText = "SELECT * FROM Catalog WHERE ParentId =" + parentId;
SqlCommand myCommand = new SqlCommand(cmdText,connection);
//connection.Open();
SqlDataReader sdr = myCommand.ExecuteReader();
while( sdr.Read() )
{
   int id = Int32.Parse(sdr["Id"].ToString());
   int parentid = Int32.Parse(sdr["ParentId"].ToString());
   string title = sdr["Title"].ToString();
   ctr_catalog_editlist.Items.Add(new ListItem(title,id.ToString()));
   //sdr.Close();
   OrderTree(connection,id);
 }
}这个递归方法在JAVA中实现应该没问题,因为JAVA中的ResultSet可以在一个连接中出现很多次,但是
在ASP.NET中就出现问题了,在一个连接中SqlDataReader好像只能使用一次,编译的时候系统提示没有关闭SqlDataReader对象。这是我第一次做这个东西,请高手指点一下,有没有好的算法,总觉得这个算法的效率太低了,每显示一下都要查询这么多次数据库。或者帮忙解决一下我的算法里出现的问题。如何使用SqlDataReader.谢谢!!

解决方案 »

  1.   

    这里使用DataTable来遍历内存数据集应该更合适一些。
      

  2.   

    把所有的数据一次性全部取出来放到DataTable中去,然后再递归遍历,这样可能比你现在算法要好得多。
      

  3.   

    我重新实现了一下,把数据先放在DataSet中,然后再递归遍历,具体实现如下:
    public void OrderTreePro( int parentid )
    {
        string select = "ParentId = " + parentid;
        DataRow[] rows = dataset.Tables[0].Select( select ,null);
        foreach ( DataRow row in rows)
        {
    int id = Int32.Parse(row["Id"].ToString());
             int parentId = Int32.Parse(row["ParentId"].ToString());
    string title = row["Title"].ToString();
    ctr_catalog_editlist.Items.Add( new ListItem( title, id.ToString()));
    OrderTreePro( parentId );
         }

    }public void BindDataSet()
    {
       SqlConnection myConnection = connectDB.getConnection();
       string cmdText = "SELECT * FROM Catalog";
       SqlDataAdapter sda = new SqlDataAdapter(cmdText,myConnection);
       myConnection.Open();
      sda.Fill( dataset ,"Catalog" );
      myConnection.Close();
    }这个算法只要一递归就会出现:“JIT调试失败,出现以下错误,拒绝访问”
    如果不递归的话能够正常的显示,请问哪位知道出什么问题了吗,怎样解决阿?谢谢~!!!!
      

  4.   

    先把数据存放在DateSet中,然后对DataTable进行操作