Articles in this section
Category / Section

How to populate TreeNavigator from DataBase?

2 mins read

In WF TreeNavigator there is no default support to bind the items through Database and it can be achieved by loading the TreeMenuItem by iteration process from DataView. This can be done by below steps,

  • Initialize the DataView with required data.
  • Add the DataView rows to TreeMenuItems by iteration process.
  • Populate the TreeNavigator by TreeMenuItem.

C#

//Initialize the DataView
private DataView dataBaseView;
public Form1()
{
   InitializeComponent();
   dataBaseView = GetOrderDetials();
}
 
private static DataView GetOrderDetials()
{
    try
    {
         //Initialize the DataSet
         DataSet ds = new DataSet();
         using (SqlCeConnection con = new SqlCeConnection(@"DataSource=Data\Northwind.sdf"))
         {
             con.Open();
             SqlCeCommand cmd = new SqlCeCommand("SELECT Top(20) [Order ID], [Product ID], [ColumnName], [Unit Price], Quantity \r\nFROM [Order Details] ", con);
             SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
             da.Fill(ds);
 
             // Creation of DataView
             DataView dataView = new DataView(ds.Tables[0], "[Unit Price] >= 20", "[Order ID]", DataViewRowState.CurrentRows);
             return dataView;
         }
    }
    catch (Exception e)
    {
        MessageBox.Show("Exception in connection: " +  e.Message);
        return null;
    }
}
 
private void button1_Click(object sender, EventArgs e)
{
    this.treeNavigator1.Visible = true;
    FillItems(this.treeNavigator1);
}
 
private void FillItems(TreeNavigator tree)
{
    foreach (DataColumn col in dataBaseView.Table.Columns)
        this.treeNavigator1.Items.Add(new TreeMenuItem() { Text = col.ColumnName });
    //Add the DataView rows to TreeMenuItem
    foreach (DataRow x in dataBaseView.Table.Rows)
    {
        foreach (TreeMenuItem y in this.treeNavigator1.Items)
        {
            if (dataBaseView.Table.Columns.Contains(y.Text))
               y.Items.Add(new TreeMenuItem() { Text = x[dataBaseView.Table.Columns[y.Text]].ToString() });
        }
    }
}

 

Populate winforms treenavigator to database

 

View sample in GitHub

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied