我正在开发一个 Windows 应用商店应用程序,它有许多列表框来从数据库检索数据, 这是我的 MySQL 数据库屏幕截图
之后数据库列表框中的空值不会填充数据,如下图所示
我想将列表框中的 Null 值保留为空并存储其他详细信息我该怎么做
这是 C# 代码
private void Button_View_Click(object sender, RoutedEventArgs e)
{
listb0.Items.Clear();
listb1.Items.Clear();
listb2.Items.Clear();
listb3.Items.Clear();
listb4.Items.Clear();
try
{
string Query = @"SELECT * FROM `bcasdb`.`tbl_results`;";
//This is command class which will handle the query and connection object.
MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();// this query will be executed and data saved into the database.
while (MyReader.Read())
{
ListBoxItem itm0 = new ListBoxItem();
itm0.Content = MyReader.GetString(0);
this.listb0.Items.Add(itm0);
ListBoxItem itm1 = new ListBoxItem();
itm1.Content = MyReader.GetString(1);
this.listb1.Items.Add(itm1);
ListBoxItem itm2 = new ListBoxItem();
itm2.Content = MyReader.GetString(2);
this.listb2.Items.Add(itm2);
ListBoxItem itm3 = new ListBoxItem();
itm3.Content = MyReader.GetString(3);
this.listb3.Items.Add(itm3);
ListBoxItem itm4 = new ListBoxItem();
itm4.Content = MyReader.GetString(4);
this.listb4.Items.Add(itm4);
}
conn.Close();
}
catch (Exception)
{
errormsgBox();
}
}
最佳答案
如果您希望在代码中解决此问题,则需要使用 DataReader 的 DBNull 方法检查 DBNull
ListBoxItem itm2 = new ListBoxItem();
itm2.Content = MyReader.IsDBNull(2) ? "" : MyReader.GetString(2);
this.listb2.Items.Add(itm2);
当然,这种模式应该应用于其他可能为空的列。
关于c# - 如何在列表框中存储空值c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26437878/