treeview - database
Hi,
In my page, i used the tree view node retrieved from mysql db.
The following code generate error as Specified cast is not valid.
ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TreeViewCS.aspx.cs" Inherits="TreeViewCS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>TreeView Sample in C#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView
ID="TreeView1"
ExpandDepth="0"
PopulateNodesFromClient="true"
ShowLines="true"
ShowExpandCollapse="true"
runat="server"
OnTreeNodePopulate="TreeView1_TreeNodePopulate" />
</div>
</form>
</body>
</html>
C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Odbc;
public partial class TreeViewCS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateRootLevel();
}
private void PopulateRootLevel()
{
OdbcConnection objConn = new OdbcConnection(@"Driver={MySQL ODBC 3.51 Driver};server=localhost;user=root;password=root;o ption=3;DATABASE=ems");
OdbcCommand objCommand = new OdbcCommand(@"select id,title,imageurl,(select cast(count(*) as unsigned) FROM menu_details WHERE parentid=sc.id) as childnodecount FROM menu_details sc where parentID =0", objConn);
OdbcDataAdapter da = new OdbcDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, TreeView1.Nodes);
}
private void PopulateSubLevel(int parentid,TreeNode parentNode)
{
OdbcConnection objConn = new OdbcConnection(@"Driver={MySQL ODBC 3.51 Driver};server=localhost;user=root;password=root;o ption=3;DATABASE=ems");
OdbcCommand objCommand = new OdbcCommand(@"select id,title,imageurl, (select cast(count(*) as unsigned) FROM menu_details WHERE parentid=sc.id) as childnodecount FROM menu_details sc where parentID=@parentID", objConn);
objCommand.Parameters.Add("@parentID", OdbcType.Int).Value = parentid;
OdbcDataAdapter da = new OdbcDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, parentNode.ChildNodes);
}
protected void TreeView1_TreeNodePopulate(object sender,TreeNodeEventArgs e)
{
PopulateSubLevel(Int32.Parse(e.Node.Value),e.Node) ;
}
private void PopulateNodes(DataTable dt,TreeNodeCollection nodes)
{
foreach( DataRow dr in dt.Rows)
{
TreeNode tn=new TreeNode();
tn.Text = dr["title"].ToString();
tn.Value = dr["id"].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0); // Specified cast is not valid
}
}
}
Thanks in advance,
Murugavel
|