'无法将类型为'System.String'的对象转换为类型为'System.Windows.Controls.ComboBoxItem

时间:2019-01-14 01:07:46

标签: c# wpf

我到目前为止所拥有的:

  private void Grid_Loaded(object sender, RoutedEventArgs e)
    {
        SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);
        con1.Open();
        #endregion


        SqlCommand  ss = new SqlCommand("Select MorabiName From MorabiTable", con1);
        SqlDataReader s = ss.ExecuteReader();




        while (s.Read())

        {
            MorabiComboBox.Items.Add(s[0]).ToString();
        }
    }

以及我要查找的ComboBoxItem值

  if (this.MorabiComboBox == null)
            return;

        var combo = (ComboBox)sender;
        var selectedValue = (ComboBoxItem)combo.SelectedValue;
        SQLToRun SQLtoRun = new SQLToRun();
        MorabiID = await SQLtoRun.SQLToString(PublicVar.ConnectionString, "Select (MorabiID) from MorabiTable where MorabiName = ") + selectedValue;

但是当我构建程序时,它会向我显示错误 var selectedValue = (comboBoxItem)combo.selectedValue并告诉

  

$ exception {“无法将类型为'System.String'的对象转换为类型为'System.Windows.Controls.ComboBoxItem'。”} System.InvalidCastException

我还应该做什么?

3 个答案:

答案 0 :(得分:2)

首先,此ToString语句是完全多余的

MorabiComboBox.Items.Add(s[0]).ToString();

第二个combo.SelectedValue是字符串,请看上面的行。将其强制转换为ComboBoxItem毫无意义。查看名称SelectedValue,它会告诉您它是什么。

以下内容更有意义

var selectedValue = (string)combo.SelectedValue

最后,

考虑使用Parameterized Queries而不使用字符串进行SQL查询

答案 1 :(得分:0)

 MorabiComboBox.Items.Add(s[0].ToString());

使用它,这次它将起作用。

答案 2 :(得分:0)

如果要使用ComboBoxItem,请在Grid_Loaded事件处理程序中创建一个:

MorabiComboBox.Items.Add(new ComboBoxItem { Content = s[0].ToString() });

然后您可以将SelectedItem属性投射到ComboBoxItem

var selectedValue = combo.SelectedItem as ComboBoxItem:

如果将字符串添加到Items集合中,则应将SelectedItem属性强制转换为string

var selectedValue = combo.SelectedItem as string;

类型必须匹配。