![](/img/trans.png)
[英]"System.NullReferenceException" Error While Using Linq
[英]System.NullReferenceException in while using Linq Xamarin
解決了
我有一個從名為Strategy的類創建的SQLite Table,它具有兩個屬性String StrategyCode
和String StrategyID
。 我使用此代碼將StrategyCode列綁定到Spinner。
private void BindList()
{
try
{
var list = connection.Query<Strategy>("SELECT StrategyCode FROM Strategy");
BindStrategy = list.ConvertAll(x => Convert.ToString(x));
var StratAdpater = new ArrayAdapter<System.String>(this, Resource.Layout.spinner_item, BindStrategy);
StratAdpater.SetDropDownViewResource(Resource.Layout.spinner_item);
spinner2.Adapter = StratAdpater;
}
catch(Exception e)
{
Toast.MakeText(this, e.ToString(), ToastLength.Long).Show();
}
}
我有權低於這個微調,在哪里,我想展現一個TextView StrategyID
從微調選擇相應StrategyCode的。 這就是我的做法。
try
{
var selectedstrat = spinner2.SelectedItem.ToString();
var userselection = (from a in connection.Table<Strategy>()
where a.StrategyCode == selectedstrat
select a);
strategyID.Text = userselection.FirstOrDefault().StrategyID;
}
catch (Exception e)
{
Toast.MakeText(this, e.ToString(), ToastLength.Long).Show();
}
但是我正在獲取System.NullReferenceException-(對象引用未設置為對象的實例),並且StrategyID尚未設置為Textview。 但是,當我使用HardCode表示StrategyCode
值時,例如:
var userselection = (from a in connection.Table<Strategy>()
where a.StrategyCode == "Strategy1"
select a);
然后,TextView顯示硬編碼策略的ID。 這里可能出什么問題了? 我試過了
var userselection = (from a in connection.Table<Strategy>()
where a.StrategyCode == selectedstrat
select a.StrageyID).FirstOrDefault();
StrategyID.Text = userselection.ToString();
但是我仍然無法在TextView上獲取StrategyID。
讓我們看一下這一行:
var userselection = (from a in connection.Table<Strategy>() where a.StrategyCode == selectedstrat select a.StrageyID).FirstOrDefault();
如果userselection
為null
怎么辦?
StrategyID.Text = userselection.ToString(); ^^^^^^^^^^^^^ <- null => throws
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.