Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to load and view first item from xamarin sql database in C#

ycusoyycusoy Member ✭✭

I use helper code below to get the first ID from MyTable but an error. How should this code be made accessible?

public Task<MyTable> GetLastTableItem(int id)
{
    return _db.Table<MyTable>().Where(i => i.ID == id).FirstOrDefaultAsync();
}

Then I want to display it in label. How should this be made?

void GetLastItem(object sender, EventArgs e)
{
  Label label = new Label()
  label.Text = bla''bla''bla.GetLastTableItem();
}
Tagged:

Best Answer

  • YelinzhYelinzh Member, Xamarin Team Xamurai
    edited January 29 Accepted Answer

    @ycusoy The readonly modifier cannot be used in a method, try placing the code in the page class instead.

    readonly SQLiteAsyncConnection database;
    public void ReadButton_Clicked(object sender, EventArgs e)
    {
        var item = database.GetLastTableItem(1).Result;
        label.Text = item.Name;
    }
    

Answers

  • YelinzhYelinzh Member, Xamarin Team Xamurai
    edited January 28

    The GetLastTableItem method returns a result that is type of Task<MyTable>, you could get the item data from the result and pass the value of the related property to the label.

    Check the code:

    private void ReadButton_Clicked(object sender, EventArgs e)
    {
        var item = database.GetLastTableItem(1).Result;
        label.Text = item.Name; //the value should be type of string
    }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • ycusoyycusoy Member ✭✭

    I tried but it didn't work and an error ,,

  • YelinzhYelinzh Member, Xamarin Team Xamurai

    What error occured? Please post the details about the error log.

  • ycusoyycusoy Member ✭✭

    like this it looks like

  • YelinzhYelinzh Member, Xamarin Team Xamurai
    edited January 29 Accepted Answer

    @ycusoy The readonly modifier cannot be used in a method, try placing the code in the page class instead.

    readonly SQLiteAsyncConnection database;
    public void ReadButton_Clicked(object sender, EventArgs e)
    {
        var item = database.GetLastTableItem(1).Result;
        label.Text = item.Name;
    }
    
  • ycusoyycusoy Member ✭✭

    @Yelinzh said:

    Thank @Yelinzh <3

Sign In or Register to comment.