如何在C#中将sql数据库中表的列名添加到组合框# [英] How to get column names of a table in sql database to combobox in C#
问题描述
您好,先生,
我在访问combobox时陷入困境。如何在调试后从MSSQL数据库中获取单列值到组合框中。
这里我在C#中使用了这段代码:
<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<< <<<<<< br mode =hold/>
Hello sir,
Am get stuck in accessing into combobox.How to get single column value into the combobox from MSSQL database after debugging.
Here i have used this code in C#:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<br mode="hold" />
SqlConnection con;
SqlCommand com;
SqlDataReader dr;
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
con = new SqlConnection("Data Source=CBP\\SQLEXPRESS;Initial Catalog=ECG;Integrated Security=True");
com = new SqlCommand("Select Device_name from Monitor_devices", con);
//cmd.CommandType = CommandTypeText;
dr=com.ExecuteReader();
//int j = 0;
//if (dr.HasRows)
//{
while (dr.Read())
{
comboBox2.Items.Add(dr[0].ToString());
//j++;
}
dr.Close();
con.Close();
}
>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>
任何人都知道这一点,请帮忙..
谢谢,
Pradeep CBZ
编辑:标签已添加
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Any one know about this ,plz do help..
Thanks,
Pradeep CBZ
Tags added
推荐答案
尝试
try
comboBox2.Items.Add(dr[0].ToString());
to
to
comboBox2.Items.Add(dr["Device_name"].ToString());
你也不需要在comboBox2_SelectedIndexChanged事件中拥有代码,你删除那个事件......见下文
Also you do not need to have the code in a "comboBox2_SelectedIndexChanged" event, you an remove that event... see below
SqlConnection con;
SqlCommand com;
SqlDataReader dr;
con = new SqlConnection("Data Source=CBP\\SQLEXPRESS;Initial Catalog=ECG;Integrated Security=True");
com = new SqlCommand("Select Device_name from Monitor_devices", con);
//cmd.CommandType = CommandTypeText;
con.Open();
dr=com.ExecuteReader();
//int j = 0;
//if (dr.HasRows)
//{
while (dr.Read())
{
comboBox2.Items.Add(dr["Device_name"].ToString());
//j++;
}
dr.Close();
con.Close();
你好
我使用实体框架使用了这段代码:
Hello
I have used this code using Entity Framework :
Public Class BankAccount
{
Public List<ema.shopping.model.bank> GetBank();
{
using(ShoppingEntities _ShoppingEntities = new ShoppingEntities())
{
return _ShoppingEntities.Bank.ToList();
}
}
}
</ema.shopping.model.bank>
并为您提供表格代码背后:
and for you Form Code Behind:
class.BankAccount _BankAccount = new BankAccount();
BankIDCombobox.DisplayName = "Name";
BankIDCombobox.ValueMember = "BankID";
BankIDCombobox.DataSource = _BankAccount.GetBank();
希望它能解决您的问题
最好的问候
hope it will solve your problem
best regards
SqlConnection con;
string dbConnectionString = @"Data Source=CBP\\SQLEXPRESS;Initial Catalog=ECG;Integrated Security=True";
string sqlTable = null;
con = new SqlConnection(dbConnectionString);
con.Open();
sqlTable = "Select Device_name from Monitor_devices";
SqlDataAdapter dscmd = new SqlDataAdapter(sqlTable, con);
DataSet ds = new DataSet();
dscmd.Fill(ds);
comboBoxColumn.DataSource = ds.Tables[0];
comboBoxColumn.DisplayMember = "Device_name";
con.Close();
这篇关于如何在C#中将sql数据库中表的列名添加到组合框#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!