Issue
I have a very short question, I have a project built with Xamarin. I am using realm db in this project. And what I want to do is delete all data on realm db whenever I press a button. I can do this in listview with item selected, but I want to delete all data with a single button.
Thank you in advance for your help. Stackoverflow has taught me a lot.
Solution
I am using realm db in this project. And what I want to do is delete all data on realm db whenever I press a button. I can do this in listview with item selected, but I want to delete all data with a single button.
If you want to delete all Realm Db record , please take a look the following code.
My model,
public class Student : RealmObject
{
[PrimaryKey]
public int StudentID { get; set; }
public string StudentName { get; set; }
}
MainPage
<StackLayout>
<ListView x:Name="listStudent">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding StudentName}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button
x:Name="Addbtn"
Clicked="Addbtn_Clicked"
Text="add data" />
<Button
x:Name="deletebtn"
Clicked="deletebtn_Clicked"
Text="delete all data" />
</StackLayout>
public partial class Page30 : ContentPage
{
public Page30()
{
InitializeComponent();
}
private void Addbtn_Clicked(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
for (int i = 0; i < 20; i++)
{
Student item = new Student()
{
StudentID = i,
StudentName = "cherry " + i
};
realmDB.Write(() =>
{
realmDB.Add(item);
});
}
List<Student> students = realmDB.All<Student>().ToList();
listStudent.ItemsSource = students;
}
private void deletebtn_Clicked(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
realmDB.Write(() =>
{
realmDB.RemoveAll();
});
List<Student> students = realmDB.All<Student>().ToList();
listStudent.ItemsSource = students;
}
}
Answered By - Cherry Bu - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.