简体   繁体   中英

how do populate treelist view with checkbox nodes

Guys i want to populate a tree list view with nodes using the data from my database table (sql server) by looping it can anybody can give some idea. I don't know where to start my coding. im using this code to get data and connect to the database. and the treelist view is at the winform.

SqlConnection cn = new SqlConnection();
SqlCommand cmd4 = new SqlCommand();
con.OpenConnections();
cmd4.Connection = cn;
cmd4.CommandType = CommandType.Text;
cn.ConnectionString = con.connections1;
cmd4.CommandText = "Select cmodname from modules";

don't know what to use next. reader or datatable?

Should be something like this:

You need to make checks for null's and stuff you don't want to appear.

private void FillTreeView(string connectionString)
{
    string query = "Select cmodname from modules;";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        SqlDataReader sqlReader = command.ExecuteReader();
        try
        {
            while (sqlReader.Read())
            {
                     if (treeView2.SelectedNode != null)
                     {
                         treeView2.SelectedNode.Nodes.Add(sqlReader[0]);
                         treeView2.ExpandAll();
                     }
                     else
                     {
                         treeView2.Nodes[0].Nodes.Add(sqlReader[0]);
                     }

          }
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            sqlReader.Close();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM