[英]How do I resync the Visual Studio 2008 Windows Forms Designer?
[英]How do I load a Windows Forms Combobox, with MSSQL Database data in Visual Studio?
我一直在尝试将MSSQL数据添加到Windows Forms Combobox的不同方法,但是已经无法正常工作了。 我一定想念一些东西,但我不知道可能是什么。
我试图在名为StudentDatabase的SQL数据库中,从名为Course的表中添加Description数据。
我正在使用Microsoft SQL Management Studio 2018和Visual Studio 2017。
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillCombobox();
}
void FillCombobox()
{
string sql = "SELECT * FROM Course";
SqlConnection dbConn = new SqlConnection("Data Source = localhost; Initial Catalog = StudentDatabase; Integrated Security = SSPI");
SqlCommand dbComm = new SqlCommand(sql, dbConn);
SqlDataReader myReader;
try
{
dbConn.Open();
myReader = dbComm.ExecuteReader();
while (myReader.Read())
{
string Desc = myReader["Description"].ToString();
comboBox1.Items.Add(Desc);
}
}
catch(Exception ex)
{
MessageBox.Show("Error");
}
}
}
}
我希望“ Combox”框充满不同的“课程说明”,但它仍然为空,并且没有收到任何错误消息。
尝试首先列出所有项目,然后将它们绑定到ComboBox。
List<string> _descriptions;
//Fill the list from the database
string query = "SELECT Description FROM Course";
using(SqlCommand dbComm= new SqlCommand(query, dbConn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
_descriptions.Add(reader.GetString(0));
}
}
}
//Add items to the ComboBox
foreach (string str in _descriptions)
{
comboBox1.Items.Add(str);
}
//Or add with a datasource without re-iterating
comboBox1.Datasource = _descriptions;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.