c# - 如何在列表框中存储空值c#

标签 c# mysql listbox

我正在开发一个 Windows 应用商店应用程序,它有许多列表框来从数据库检索数据, 这是我的 MySQL 数据库屏幕截图

enter image description here

之后数据库列表框中的空值不会填充数据,如下图所示

enter image description here

我想将列表框中的 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/

相关文章:

c# - 序列化 - 从流中查看对象图

c# - 没有 EntityKey 的 MemberwiseClone

WPF/MVVM 将 ListBoxItem 模板中的 CheckBox 绑定(bind)到 SelectedItem 属性

sql - 使用 SQL Server 使用多选框进行过滤

c# - 我应该为单元测试访问 protected 方法吗?

c# - 可以在文件系统中保存缩略图版本吗?通常的做法是什么?

mysql - 从另一个表更新表: Difference between using inner join and update multiple tables?

php - mysql:在查询中或在php中减去多个列?

PHP+PDO : Working MySQL Query with >10 rows always return 0 row (rowCount()==0)

带有文件超链接 mvvm 的 WPF 列表框