我正在尝试学习一些C#.net。我只是想通过Web界面公开我的C#类中包含的AdventureWorks数据库。这是设置:
我的ASPX页面上有DropDownList
,ID为tableNameDropDown
。它会在Page_Load
上填充,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
String table_names_sql = "select Name from sysobjects where type='u' ORDER BY name";
SqlCommand cmd = new SqlCommand(table_names_sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tableNameDropDown.Items.Add(reader[0].ToString());
}
conn.Close();
tableNameDropDown.AutoPostBack = true;
}
这很好用,我在DB中获得了一个很好的长表列表。当有人从列表中选择一个表格时,我想在GridView
控件中显示该表格,其ID为grid
。这就是我所拥有的:
protected void tableNameDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dataSet = new DataSet();
String tableName = columnNameDropDown.SelectedItem.ToString();
String table_sql = String.Format("SELECT * FROM {0};", tableName);
SqlDataAdapter adapter = new SqlDataAdapter(table_sql, conn);
adapter.Fill(dataSet, tableName);
grid.DataSource = dataSet;
grid.DataMember = tableName;
}
当我调试页面时,我在adapter.Fill(dataSet, tableName);
行收到错误:SqlException:Inlvalid object name' {tableName}'。
数据库中的表格如下:
dbo.AWBuildVersion
.... more dbo. tables
HumanResources.Department
HumanResources.Employee
.... more HumanResources tables
Person.Address
Person.AddressType
.... more Person tables
... Other prefixes are "Pdoduction, Purchasing, Sales"
可能有~50 +表,我把他们的所有名字(没有前缀)都写进我的DropDownList没问题,但我似乎无法查询它们。
有什么想法吗?
答案 0 :(得分:2)
您已经自己回答:您还需要在正在执行的select语句中使用前缀,例如
Select * From Person.Address
除此之外你不应该使用sysobject表,从SQL Server 2005你有系统视图可以帮助你,所以你可以写一个更好的语句来选择表:
select * From INFORMATION_SCHEMA.TABLES
同时检查this article。
此致 马西莫