2017-02-23 88 views
0

我使用這個連接字符串來連接到SQL Server如何填充從SQL Server中的樹狀動態獲得

我試圖填充節點的所有表和列名......但我不能這樣做。

我能夠得到的只是表名而不是子節點(即列名)

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()); 
     } 
    } 
}  
+0

您需要從'sys.columns'中選擇以獲取列名; 'sys.columns'中的'object_id'對應''sys.tables'中的'object_id' –

+0

感謝您的回覆。讓我試試@marc_s ... –

回答

0

我覺得這個查詢可以幫助你

從INFORMATION_SCHEMA.TABLES 從INFORMATION_SCHEMA選擇COLUMN_NAME選擇TABLE_NAME .COLUMNS where TABLE_NAME ='Table1'enter image description here

+0

嗨帕文,謝謝你的回覆。我已經在使用這個查詢來獲取表格字段和列。但我需要填充樹視圖。如何實現這一目標? SELECT T [name] AS [table_name],AC。[name] AS [column_name] FROM sys。[tables] AS T INNER JOIN sys。[all_columns] AC ON T. [object_id] = AC。[object_id] –