【问题标题】:XamarinForms ExceptionXamarin 表单异常
【发布时间】:2018-06-05 09:19:44
【问题描述】:

我创建了一个带有数据库连接的搜索栏。当我运行它时。它得到一个例外。我使用的是之前创建的数据库。

模型类条目

public class entries
{
    public entries()
    {

    }

    public entries(string word)
    {
        this.word = word;
    }
    public entries(string word, string wordtype, string definition)
    {
        this.word = word;
        this.wordtype = wordtype;
        this.definition = definition;
    }   
    public string word
    { get; set; }

    public string wordtype
    { get; set; }

    public string definition
    { get; set; }

    public List<string> GetWord { get; set; }
}

类数据库管理器:

public class DatabaseManager
{
    SQLiteConnection dbConnection;
    public DatabaseManager()
    {
        dbConnection = DependencyService.Get<ISQLite>().GetConnection();
    }



    public List<string> GetWord()
    {
        return dbConnection.Query<string>("Select word From [entries]").ToList();
    }


}

MainPage.xaml.cs:

    DatabaseManager dbManager = new DatabaseManager();
 private void MySearchBar_SearchButtonPressed(object sender, EventArgs e)
        {

        }

        private void MySearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            var keyword = MySearchBar.Text;
            if(keyword.Length >= 1) { 
                var suggestions = dbManager.GetWord().Where(c => c.ToLower().Contains(keyword.ToLower()));

                SuggestionListView.ItemsSource = suggestions;
                SuggestionListView.IsVisible = true;
            }
            else
            {
                SuggestionListView.IsVisible = false;
            }
        }

这是例外:

System.MissingMethodException:'System.String' 类型的构造函数不是 找到了。

请帮忙。太感谢了。

【问题讨论】:

  • “我是...的新手”通常意味着“我懒得使用谷歌”。请不要这样开始你的帖子。
  • 哪一行抛出异常?
  • 谢谢杰森!!这是引发异常的行: return dbConnection.Query("Select word From [entries]").ToList();
  • @TanVuBoyGib 您需要提供一个只有一个字符串属性的类,然后您可以使用 Linq 投影将这些查询结果转换为字符串列表

标签: xaml xamarin xamarin.forms xamarin.ios xamarin.android


【解决方案1】:

您可能已经为“条目”表创建了一个实体,例如它是,

[Table (“entries”)]
public class Entries
{
    …

    [Column (“word”)]
    public string Word;

    …
}

然后换行

dbConnection.Query<string>("Select word From [entries]").ToList();

dbConnection.Table<Entries>().Select(x => x.Word).ToList();

这将消除创建一个附加类的要求,如 Sushi 在上面的评论中所说。

此外,如果任何单词包含Null,以下行将在c.ToLower() 处抛出NullReferenceException

dbManager.GetWord().Where(c => c.ToLower().Contains(keyword.ToLower()));

所以要摆脱这种情况,请选择不具有空值的结果,例如,

dbConnection.Table<Entries>().Where(x => x.Word != null).Select(x => x.Word).ToList();

【讨论】:

  • 非常感谢你们。向你致以最良好的祝愿,@MilanG。太感谢了。这真的对我有用。
猜你喜欢
  • 2019-10-02
  • 2019-05-21
  • 2019-06-20
  • 1970-01-01
  • 2022-07-29
  • 1970-01-01
  • 2016-04-27
  • 2018-05-25
  • 1970-01-01
相关资源
最近更新 更多