【问题标题】:How do I populate a ListView with data from a SQLite database如何使用 SQLite 数据库中的数据填充 ListView
【发布时间】:2019-06-10 21:47:12
【问题描述】:

我正在使用 Xamarin 表单构建跨平台移动应用程序。我现在遇到的问题是:我有一个页面,我想在页面上的ListView 中显示来自数据库的信息。 sqlite 数据库中还有两个表。

  1. 首先,我为页面创建了 OnAppearing 方法的覆盖,以便在页面出现时显示数据。

  2. 然后我在里面打开了一个 sqlite connect 像这样

    using(SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
    {
      //about to put the code here in the next step
    }
    
  3. 然后在里面我尝试像这样从数据库创建表(“ModelName”是指保存与 sqlite 数据库中的数据对齐的模型的类的名称)

    conn.CreateTable<ModelName>
    
  4. 然后尝试使用查询,然后像这样将其设置为 ListView 的 ItemSource

    ListViewName.ItemSource = conn.Query<ModelName>("SELECT * FROM databaseTableName;");
    
  5. 在前端,我已经像这样设置了数据绑定。

    <ListView x:Name="ListViewName">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding ModelName}" Detail="{Binding ModelName}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    

注意:我也尝试过像这样设置绑定

Text="{Binding ColumnNameFromTable}"

当我运行它时,我收到一条错误消息,指出该表不存在,但我在项目中有 sqlite 数据库(在 android 项目的 assets 文件夹和 iOS 项目的 resources 文件夹中) 桌子就在那里。所以我不知道我哪里错了

还要回答关于什么的问题

(App.DatabaseLocation)

分别在MainActivity.cs和AppDelegate.cs中设置如下

//in MainActivity.cs
string dbName = "DatabaseName.db";
string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string fullPath = Path.Combine(folderPath, dbName);
LoadApplication(new App(fullPath));
//in AppDelegate.cs
string dbName = "DatabaseName.db";
string folderPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"..", "Library");
string fullPath = Path.Combine(folderPath, dbName);
LoadApplication(new App(fullPath));

我很感激任何比我能提供的更聪明的人的帮助。感谢您花时间阅读并回答我的问题。我欠你我永远的感激之情!

【问题讨论】:

  • App.DatabaseLocation 等于什么?
  • 我已将该信息添加到问题的主体中。非常感谢您查看它并告诉我您是否知道我哪里出错了
  • 您是否尝试过直接将路径用作字符串? using(SQLiteConnection conn = new SQLiteConnection("fullPath"))
  • 我试过了。但由于它是跨平台的,因此在 android 和 ios 项目文件和(即 MainActivity.cs 和 AppDelegate.cs)中生成的完整路径字符串不同但正因为如此,当我尝试在 searchpage.cs 上使用“fullPath”时不知道从哪里得到它。但由于跨平台因素,我无法在 searchpage.cs 中构建字符串

标签: c# visual-studio sqlite xaml


【解决方案1】:

如果您使用的是 Xamarin Forms,则无需在 MainActivity.cs 和 AppDelegate.cs 中为本地数据库设置任何内容。 阅读本指南将最好地解释如何在 Xamarin Forms 上使用 sqllite https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/databases

可以在这里找到简单的示例代码: https://github.com/xamarin/xamarin-forms-samples/tree/master/Todo 此示例已将数据检索到您想要的列表视图中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多