[英]Unable to cast the type 'System.String' to type 'System.Object'
[英]'Unable to cast object of type 'System.String' to type 'System.Windows.Controls.ComboBoxItem
到目前為止我所擁有的:
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
我還應該做什么?
首先這個ToString
語句是完全多余的
MorabiComboBox.Items.Add(s[0]).ToString();
其次combo.SelectedValue
是字符串,看上面那行。 將其轉換為ComboBoxItem
沒有任何意義。 看看名字SelectedValue
它告訴你它是什么。
以下內容會更有意義
var selectedValue = (string)combo.SelectedValue
最后,
考慮使用Parameterized Queries
而不是串聯字符串來進行 SQL 查詢
如果你想要一個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;
類型必須匹配。
MorabiComboBox.Items.Add(s[0].ToString());
使用這個,這次它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.