I think my sample meets your requirement. In that sample, there are two tables: MainCategory and SubCategory.
The table structures are:
CREATE TABLE MainCategory (MainCategoryID int, MainCategoryText varchar(20))
INSERT INTO MainCategory
SELECT 1, 'Sport' UNION ALL
SELECT 2, 'Travel' UNION ALL
SELECT 3, 'Job'
CREATE TABLE SubCategory (SubCategoryID int, SubCategoryText varchar(20), MainCategoryID int)
INSERT INTO SubCategory
SELECT 1, 'Football',1 UNION ALL
SELECT 2, 'Baseball',1 UNION ALL
SELECT 3, 'Engineer',3 UNION ALL
SELECT 4, 'Swim', 1 UNION ALL
SELECT 5, 'America', 2
We use FOR XML AUTO to generate the XML data:
SELECT MainCategoryText,SubCategoryText FROM MainCategory
INNER JOIN SubCategory
ON MainCategory.MainCategoryID = SubCategory.MainCategoryID
FOR XML AUTO, ROOT('Categories')
Then we populate the TreeView control with returned XML data as follows:
WebForm1.aspx
<asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource><asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1"
AutoGenerateDataBindings="False"><DataBindings><asp:TreeNodeBinding DataMember="Categories" Text="Categories"
Value="Categories" /><asp:TreeNodeBinding DataMember="MainCategory" TextField="MainCategoryText"
ValueField="MainCategoryText" /><asp:TreeNodeBinding DataMember="SubCategory" TextField="SubCategoryText"
ValueField="SubCategoryText" /></DataBindings> </asp:TreeView>
WebForm1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
XmlDataSource1.Data = GetXmlDoc().OuterXml;
}
protected XmlDocument GetXmlDoc()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ToString()))
{
conn.Open();
string strsql = "SELECT MainCategoryText,SubCategoryText FROM MainCategory ";
strsql += "INNER JOIN SubCategory ON MainCategory.MainCategoryID = SubCategory.MainCategoryID ";
strsql += "FOR XML AUTO, ROOT('Categories')";
SqlCommand comm = new SqlCommand(strsql, conn);
XmlReader reader = comm.ExecuteXmlReader();
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return doc;
}
}
My major concern is getting the treeview to update dynamically. Any suggestions, advice, books and site recomendations you may have will be greatly appreciated.
I do not quite understand you. Do you mean that the TreeView’s level is not fixed or you just want new inserted value will display in the TreeView? If the latter, the TreeView will be populated with data in SQL Server each time, so the new inserted value will display in it.
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.