已解决
我有一个从类创建的名为 Strategy 的SQLite表,它具有两个属性String StrategyCode
和String StrategyID
。我正在使用此代码将StrategyCode列绑定到微调器。
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 ,我想在其中显示从微调框选择的相应StrategyCode的StrategyID
。这就是我的做法。
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。
答案 0 :(得分:0)
让我们看看这一行:
var userselection = (from a in connection.Table<Strategy>()
where a.StrategyCode == selectedstrat
select a.StrageyID).FirstOrDefault();
如果userselection
是null
怎么办?
StrategyID.Text = userselection.ToString();
^^^^^^^^^^^^^ <- null => throws