简体   繁体   中英

How to populate a treeview from SQL Server dynamically to get all table and column names

I'm using this connection string to connect to SQL Server

I'm trying to populate nodes... but I am not able to do so.

I am able to get only table names but not child nodes (ie column names)

connetionString = "Data Source=" + textBox1.Text + ";Initial Catalog=" + comboBox1.Text + ";User ID=" + textBox2.Text + ";Password=" + textBox3.Text;

sql = "SELECT * FROM [sys].[tables]";

connection = new SqlConnection(connetionString);

TreeView mytree = new TreeView();

try
{
    connection.Open();
    command = new SqlCommand(sql, connection);
    adapter.SelectCommand = command;
    adapter.Fill(ds, "SQL Temp Table");
    adapter.Dispose();
    command.Dispose();
    connection.Close();

    treeView1.Nodes.Clear();
    treeView1.Sort();

    for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
    {
        treeView1.Nodes.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());

        for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
        {
            treeView1.Nodes.Add(ds.Tables[0].Columns[j].ToString());
        }
    }
}    

I think this query may help you

select TABLE_NAME from INFORMATION_SCHEMA.TABLES select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Table1' 在此处输入图片说明

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