【问题标题】:How to populate a treeview from SQL Server dynamically to get all table and column names如何从 SQL Server 动态填充树视图以获取所有表和列名称
【发布时间】:2017-02-23 04:27:08
【问题描述】:

我正在使用此连接字符串连接到 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());
        }
    }
}    

【问题讨论】:

  • 需要从sys.columns中选择才能获取列名; sys.columns 中的 object_id 对应于 sys.tables 中的 object_id
  • 感谢您的回复。让我试试@marc_s...

标签: sql-server winforms c#-4.0


【解决方案1】:

我认为此查询可能对您有所帮助

从 INFORMATION_SCHEMA.TABLES 中选择 TABLE_NAME 从 INFORMATION_SCHEMA.COLUMNS 中选择 COLUMN_NAME,其中 TABLE_NAME='Table1'

【讨论】:

  • 您好帕万,感谢您的回复。我已经在使用这个查询来获取表字段和列。但我需要将相同的内容填充到树视图中。如何做到这一点? 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]跨度>
猜你喜欢
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 2011-05-01
  • 2013-04-27
  • 2022-01-24
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多