C# 如何从SQL Server 2014数据库中的选定表中获取字段?
这是我的代码:C# 如何从SQL Server 2014数据库中的选定表中获取字段?,c#,sql-server,C#,Sql Server,这是我的代码: namespace Modulul_3_proiect { public partial class FormSimpleWizard : Form { public FormSimpleWizard() { InitializeComponent(); incarcaComboBoxSimpleWiz(comboBoxWS); } //method
namespace Modulul_3_proiect
{
public partial class FormSimpleWizard : Form
{
public FormSimpleWizard()
{
InitializeComponent();
incarcaComboBoxSimpleWiz(comboBoxWS);
}
//method to extract tables from BD
public IList<string> ListTables()
{
DBConnection db = DBConnection.getConexiune;
SqlConnection conexiune = db.conn;
List<string> tables = new List<string>();
DataTable dt = conexiune.GetSchema("Tables");
foreach (DataRow row in dt.Rows)
{
string tablename = (string)row[2];
tables.Add(tablename);
}
return tables;
}
//method to load combobox with tables
private void incarcaComboBoxSimpleWiz(ComboBox cb)
{
IList<string> tabeleWizard=ListTables();
cb.Items.Clear();
cb.Items.Add("Select tables");
foreach (String tip in tabeleWizard)
cb.Items.Add(tip);
cb.SelectedIndex = 0;
}
}
}
在从SQL Server数据库中加载包含表的组合框后,我希望在组合框中获取所选表的字段,并将其显示在文本框多行中,以便在加载后进行查询
public string[] getColumnsName(string tname)
{
List<string> listacolumnas=new List<string>();
using (SqlConnection connection = new SqlConnection(Connection))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select c.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id and t.name = tname and t.type = 'U'";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
listacolumnas.Add(reader.GetString(0));
}
}
}
return listacolumnas.ToArray();
}
是否确实传入了正确的表名
试试这个
从sys.columns中选择c.name c internal join sys.tables t on t.object\U id=c.object\U id,t.name='your table name'和t.type='U'
在t-sql上这样做有什么具体问题吗?我尝试了您建议的方法,但当我尝试将它们加载到文本框时,会引发异常,对象引用未设置为对象的实例。此函数返回的值似乎为null。我不太理解命令中的代码。你能解释一下吗?我刚开始使用C,所以我不是很熟练。从sys.columns中选择C.name,然后在t.object\U id=C.object\U id和t.name='your table name'和t.type='U'上的sys.columns C internal join sys.tables t尝试上面的sql语句和'your table name'