如何从listview和数据库中删除项



我需要从listview中删除一个项目,并立即从Mysql数据库中删除,下面提供的代码将从数据库中添加这些相同的项目xaml中的代码:

<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label x:Name="NUMER" TextColor="#9e0816" FontSize="Default" Text="{Binding Name}"></Label>
<Button x:Name="och" Text="Delete" Clicked="och_Clicked"
HorizontalOptions="Center"
TextColor="#9e0816"
CornerRadius="50"
BackgroundColor="Transparent"
BorderColor="#9e0816"
BorderWidth="1.5"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

c#中的代码:

{
base.OnAppearing();
con.cn.Open();
command = new MySqlCommand("SELECT seriil FROM ISTORIYA", con.cn);
var rd = command.ExecuteReader();
hystories = new List<hystory>();
while(rd.Read())
{
hystories.Add(new hystory
{
Name = rd.GetString("seriil"),
}
);
}
rd.Close();
listview.ItemsSource = hystories;
con.cn.Close();
}

可以使用MenuItem Clicked事件来激活删除操作。然后你应该得到current selected item作为方法的参数,然后在数据库中删除它,最后更新当前的listview项目。

下面是xaml代码:
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem  Text="Delete" IsDestructive="True" Clicked="MenuItem_Deleted"></MenuItem>
</ViewCell.ContextActions>
<StackLayout>
<Label x:Name="NUMER" TextColor="#9e0816" FontSize="Default" Text="{Binding Name}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

下面是删除选中项目的伪代码,我使用的SQLite应该与Mysql类似。


private async void MenuItem_Deleted(object sender, EventArgs e)
{
//get the selected item
User user = (sender as MenuItem).BindingContext as User;
bool answer = await DisplayAlert("Alert", "Please confirm the user "+ user.Name+ " will be removed!", "Yes", "No");
if (answer)
{
UserDB db = await UserDB.Instance;
//delete the selected item
_ = await db.DeleteUserAsync(user);
//update the listivew item
List<User> a = await db.GetUserAsync();
UserCollection = new ObservableCollection<User>(a);
userinfodata.ItemsSource = UserCollection;
}
}

MS官方参考链接:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/menuitem

最新更新