[英]showing data from mysql database into listbox (data selected from combobox) c#
因此,我试图将数据从数据库显示到列表框中。 但是我想看到的数据是我在组合框中选择的,所以我打开组合框选择数据,然后它应该显示一些我正在尝试的数字,但是我不确定它是否适合我
编码:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "Select ocena From filmi.film Where film = @film"; ;
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
cmdDataBase.Parameters.AddWithValue("@film", this.comboBox1.SelectedItem);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
listBox2.Items.Add(myReader);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
您应该引用要添加到列表框中的字段
listBox2.Items.Add(myReader["ocena"].ToString());
如果字段ocena可能包含空值,那么您需要
string ocenaValue = (myReader.IsDBNull(myReader.GetOrdinal("ocena")) ?
string.Empty, myReader["ocena"].ToString());
listBox2.Items.Add(ocenaValue);
最后,我建议在一次性对象周围使用“使用声明”。 这样,当您完成使用连接,命令和阅读器时,也将在异常情况下关闭它们并进行处置
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "Select ocena From filmi.film Where film = @film"; ;
using(MySqlConnection conDataBase = new MySqlConnection(constring))
using(MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cmdDataBase.Parameters.AddWithValue("@film", this.comboBox1.SelectedItem);
using(MySqlDataReader myReader = cmdDataBase.ExecuteReader())
{
while (myReader.Read())
{
string ocenaValue = (myReader.IsDBNull(myReader.GetOrdinal("ocena")) ?
string.Empty : myReader["ocena"].ToString());
listBox2.Items.Add(ocenaValue);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Ocena是数据库表还是表中的项目? 引用列名,而不是项目或数据库表,就可以获取数据。 例如
listBox2.Items.Add(myReader [“ film”]。ToString());
将为您提供柱膜中的所有物品
自您发布以来已经很久了,但是它可以帮助其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.