简体   繁体   English

如何使用 mvvm 从数据库中加载 combobox 下拉列表并在 wpf 中进行多项选择

[英]How to load combobox drop-down list from database with multiple selection in wpf using mvvm

I'm trying to populate combobox drop-down list with data from the database.我正在尝试使用数据库中的数据填充 combobox 下拉列表。 This should be loaded dynamically, on loading the window这应该在加载 window 时动态加载

View model查看 model

public class StdBasicVM
{
        private ObservableCollection<string> _sStreamCmb;
        public ObservableCollection<string> sStreamCmb
        {
            get { return _sStreamCmb; }
            set { if (_sStreamCmb != value) { _sStreamCmb = value; OnPropertyChanged("sStreamCmb"); } }
        }

        private void COMBOBOX()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["connscmag"].ConnectionString;
            using (var conn = new MySqlConnection(connectionString))
            {
                conn.Open();

                var query = "Select distinct entry FROM gidentifiers WHERE IDENTIFIER = 'STREAM' AND entry <> 'NULL'  ";
                using (var comm = new MySqlCommand(query, conn))
                {
                    using (var reader = comm.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (reader.HasRows)
                            {
                              sStreamCmb.Add(reader.GetString("entry").ToString());
                            }

                        }
                    }
                }


            }

        }

        public StdBasicVM()
        {
            COMBOBOX();
        }
}

Window Window

<ComboBox x:Name="txtStream" Grid.Row="9" Grid.Column="1" 
Text="{Binding sStream, Mode=TwoWay}" 
DisplayMemberPath="Name" 
ItemsSource="{Binding sStreamCmb}"/>

It generates an error on line sStreamCmb.Add(reader.GetString("entry").ToString()) object reference not set to an instance of an object.它在sStreamCmb.Add(reader.GetString("entry").ToString()) object 引用未设置为 object 实例的行上生成错误。

In your code you're not initialising the combo box observable collection.在您的代码中,您没有初始化组合框可观察集合。 Change this line:更改此行:

private ObservableCollection<string> _sStreamCmb;

To this:对此:

private ObservableCollection<string> _sStreamCmb= new ObservableCollection<string>();

And it should fix the issue.它应该解决这个问题。 You can highlight when this happens by adding this line in your csproj file:您可以通过在您的 csproj 文件中添加此行来突出显示何时发生这种情况:

    <WarningsAsErrors>CS0649</WarningsAsErrors>

This will treat situations like above as errors saving you having to find out at runtime.这会将上述情况视为错误,从而使您不必在运行时查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM