如何使用按钮在datagrid视图中软删除选定的行

发布于 2025-01-27 13:31:56 字数 2030 浏览 4 评论 0原文

因此,我有一个已连接到SQL Server的DataGridView,称为MyMoviedAtAdrid,并且我已经拥有我的ISDEATER属性,以及一个删除存储库,如下所示,我的Isdeleted属性会自动显示为复选框,以便检查复选框。确实是错误的

public bool DeleteMovie(Guid id)
{
       bool isDeleted = false;
       var movie =  _context.Movie.FirstOrDefault(m => m.Id == id);
       if (movie != null)
       {
            movie.IsDeleted = true;
            _context.SaveChanges();
            isDeleted = true;
       
       } 
        return isDeleted;
}

,这是我的删除按钮方法,因此,当我按下它时,它运行我的逻辑和软删除DataGridView的一行,我尝试了多个解决方案,例如使用选定的行事件处理程序来获取所选行运行存储库方法,但没有运行迄今为止的工作。

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        Movie movie = new Movie();
        
        if(MyMovieDataGrid.SelectedRow.Count > 0)
        {
          _movieRepo.DeleteMovie(movie.Id);
        }
    }

以及我的所有属性

    Movie movie = new Movie()
    {
        Id = Guid.NewGuid(),
        IsDeleted = false,
        MovieNames = MovieNameBox.Text;
     
    }
         

以及我的addMovie repostority

    public void AddMovie(Movie movie)
    {
        _context.Movie.Add(movie);
        _context.SaveChanges();

    }
      

电影存储库方法

    private NRIDataContext _context;    
    public MovieRepository()
    {
        _context = new NRIDataContext();    
    }
       
     //GetMovie repository
     
   GetMovie() 
   {
            
    
    
        var movies = _context.Movie.Where(m => m.IsDeleted 
        ==false).ToList();
        return  movie;
                                                                                                                                                                                     
   }
      
     MyMovieDataGrid.DataSource = _movieRepo.GetMovie().OrderByDescending(x => x.MovieNames.First) .ToList();
  
     

,所以我的问题是我如何使我的datagrid知道何时运行我的存储库方法,我觉得我必须以某种方式将一些代码写入iSdeleted属性是否为true的位置它选择了整个行,​​然后我运行Deletemovie方法,但是没有解决方案可以使用。

So I have a DataGridView called MyMovieDataDrid which is connected to a sql server, and I already have my IsDeleted property, and a delete repository which is shown below, by the way my IsDeleted property automatically shows up as a checkbox so if the checkbox is checked it's true if not it's false

public bool DeleteMovie(Guid id)
{
       bool isDeleted = false;
       var movie =  _context.Movie.FirstOrDefault(m => m.Id == id);
       if (movie != null)
       {
            movie.IsDeleted = true;
            _context.SaveChanges();
            isDeleted = true;
       
       } 
        return isDeleted;
}

and here is my Delete button method so when I press it, it runs my logic and soft deletes a row from the DataGridView I've tried multiple solutions like using the selected row event handler to get the selected rows then running the repository method but none have worked so far.

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        Movie movie = new Movie();
        
        if(MyMovieDataGrid.SelectedRow.Count > 0)
        {
          _movieRepo.DeleteMovie(movie.Id);
        }
    }

and my all of my properties

    Movie movie = new Movie()
    {
        Id = Guid.NewGuid(),
        IsDeleted = false,
        MovieNames = MovieNameBox.Text;
     
    }
         

and my AddMovie repostitory

    public void AddMovie(Movie movie)
    {
        _context.Movie.Add(movie);
        _context.SaveChanges();

    }
      

Movie Repository Method

    private NRIDataContext _context;    
    public MovieRepository()
    {
        _context = new NRIDataContext();    
    }
       
     //GetMovie repository
     
   GetMovie() 
   {
            
    
    
        var movies = _context.Movie.Where(m => m.IsDeleted 
        ==false).ToList();
        return  movie;
                                                                                                                                                                                     
   }
      
     MyMovieDataGrid.DataSource = _movieRepo.GetMovie().OrderByDescending(x => x.MovieNames.First) .ToList();
  
     

so my question is how do I make my Datagrid know when to run my repository method and I feel like I have to somehow make write some code to where if the IsDeleted property is true it selects the whole row then I run my DeleteMovie Method but no solutions have worked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

窗影残 2025-02-03 13:31:56

我喜欢凯伦(Karen)的方法是“应该如何完成”,但与您的写作相去甚远,我怀疑您可能不想更改当前代码,

而您的方法是您的方法,您不愿意进行基本问题。 t从单击的行中获取电影ID,您制作了一个新电影,该电影具有新的随机GUID,据推测,该指南完全不在数据库中,因为GUID不太可能重复,然后您尝试删除该数据库:

private void DeleteButton_Click(object sender, EventArgs e)
{
    //make a new movie with random id 
    Movie movie = new Movie();
    
    if(MyMovieDataGrid)
    {
        //delete the new random id
        _movieRepo.DeleteMovie(movie.Id);
    }
}

这意味着您要删除的电影的几率实际上是一个惊人的53169119831396666349161615228241121400000;如果您立即开始单击并继续前进,直到地球被阳光吞没了红色的巨人

I like Karen's approach for being more "how it should be done", but it's quite a far cry from what you've written and I suspect you might not want to change your current code massively

The basic problem with your approach is you don't get the movie id from the row that was clicked, you make a new movie which has a new random Guid which is supposedly guaranteed to not be in the database at all because Guids are very unlikely to repeat, and then you try and delete that:

private void DeleteButton_Click(object sender, EventArgs e)
{
    //make a new movie with random id 
    Movie movie = new Movie();
    
    if(MyMovieDataGrid)
    {
        //delete the new random id
        _movieRepo.DeleteMovie(movie.Id);
    }
}

this means that the odds of the movie you want deleting actually getting deleted are a staggering 5316911983139663491615228241121400000 to one; it probably won't happen if you start clicking now and keep going until the earth is engulfed by the sun going red giant ????

Retrieve the Guid you want to delete from the row clicked on; add a CellContentClicked handler and check it's the deleted button column being clicked and then pull the movie id out of the row's data bound item:

private void DGV_CellContentClick(object sender, 
DataGridViewCellEventArgs e)
{
    //don't process clicks on the header row 
    if(e.RowIndex < 0) return;

    //don't process clicks on columns other than delete
    if(e.ColumnIndex != MyMovieDataGrid.Columns["nameOfYourDeleteColumn"].ColumnIndex) return;

    
    //pull the movie from that row
    Movie movie = MyMovieDataGrid.Rows[e.RowIndex].DataBoundItem as Movie;
    
    if(MyMovieDataGrid) //I don't know what this means; a DataGridView is not a boolean
    {
        //delete the movie id
        _movieRepo.DeleteMovie(movie.Id);
    }
}
我为君王 2025-02-03 13:31:56

考虑在onModeLcreating中设置过滤器,在这种情况下,我使用的是一个名为Contact1的模型,因为我已经有一个。在下面的表中,添加iSdeleted列,但在模型中不添加。

下面显示了用于软删除行并将其从数据杂志删除的基础知识。没有适当的存储库。

public partial class Contact1 : INotifyPropertyChanged
{
    private int _contactId;
    private string _firstName;
    private string _lastName;

    public int ContactId
    {
        get => _contactId;
        set
        {
            _contactId = value;
            OnPropertyChanged();
        }
    }

    public string FirstName
    {
        get => _firstName;
        set
        {
            _firstName = value;
            OnPropertyChanged();
        }
    }

    public string LastName
    {
        get => _lastName;
        set
        {
            _lastName = value;
            OnPropertyChanged();
        }
    }

    public Contact1()
    {
        
    }

    public override string ToString() => $"{FirstName} {LastName}";

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

modelBuilder.Entity<Contact1>()
    .HasQueryFilter(contact =>
        EF.Property<bool>(contact, "isDeleted") == false);

然后在dbcontext中超编层savechanges

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new ())
{
    DoShadowyStuff();
    return base.SaveChangesAsync(cancellationToken);
}

public override int SaveChanges()
{
    DoShadowyStuff();

    return base.SaveChanges();
}

然后在doshadowlystuff中(如果状态被删除)将状态设置为修改状态。

private void DoShadowyStuff()
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries())
    {

        if (entry.State == EntityState.Deleted)
        {
            // Change state to modified and set delete flag
            entry.State = EntityState.Modified;
            entry.Property("isDeleted").CurrentValue = true;
        }
    }
}

非常基本的读取delete操作

public class Operations
{
    public static void Remove(Contact1 contact1)
    {
        using (var context = new ShadowContext())
        {
            context.Add(contact1).State = EntityState.Deleted;
            context.SaveChanges();
        }
    }

    public static List<Contact1> Contacts()
    {
        using (var context = new ShadowContext())
        {
            return context.Contacts1.ToList();
        }
    }
}

基本表单操作。单击“删除”按钮,设置当前行的状态要删除,并保存更改,以将联系人标记为修改并设置ISDEATED。接下来,从bindinglist中删除删除删除,然后从数据杂志上删除该行。

public partial class Form1 : Form
{
    private BindingList<Contact1> _bindingList;
    private readonly BindingSource _bindingSource = new ();
    public Form1()
    {
        InitializeComponent();
        Shown += OnShown;
    }

    private void OnShown(object sender, EventArgs e)
    {
        _bindingList = new BindingList<Contact1>(Operations.Contacts());
        _bindingSource.DataSource = _bindingList;
        dataGridView1.DataSource = _bindingSource;
    }

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        Operations.Remove(_bindingList[_bindingSource.Position]);
        _bindingList.RemoveAt(_bindingSource.Position);
    }
}

Consider setting up a filter in OnModelCreating in this case I'm using a model named Contact1 since I have this already. In the underlying table add the IsDeleted column but not in the model.

Below shows the basics to soft delete a row and remove it from the DataGridView. No proper repository.

public partial class Contact1 : INotifyPropertyChanged
{
    private int _contactId;
    private string _firstName;
    private string _lastName;

    public int ContactId
    {
        get => _contactId;
        set
        {
            _contactId = value;
            OnPropertyChanged();
        }
    }

    public string FirstName
    {
        get => _firstName;
        set
        {
            _firstName = value;
            OnPropertyChanged();
        }
    }

    public string LastName
    {
        get => _lastName;
        set
        {
            _lastName = value;
            OnPropertyChanged();
        }
    }

    public Contact1()
    {
        
    }

    public override string ToString() => 
quot;{FirstName} {LastName}";

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

OnModelCreating

modelBuilder.Entity<Contact1>()
    .HasQueryFilter(contact =>
        EF.Property<bool>(contact, "isDeleted") == false);

Then override SaveChanges in the DbContext

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new ())
{
    DoShadowyStuff();
    return base.SaveChangesAsync(cancellationToken);
}

public override int SaveChanges()
{
    DoShadowyStuff();

    return base.SaveChanges();
}

Then in DoShadowlyStuff if the state is Deleted set the state to modified.

private void DoShadowyStuff()
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries())
    {

        if (entry.State == EntityState.Deleted)
        {
            // Change state to modified and set delete flag
            entry.State = EntityState.Modified;
            entry.Property("isDeleted").CurrentValue = true;
        }
    }
}

Very basic read and delete operations

public class Operations
{
    public static void Remove(Contact1 contact1)
    {
        using (var context = new ShadowContext())
        {
            context.Add(contact1).State = EntityState.Deleted;
            context.SaveChanges();
        }
    }

    public static List<Contact1> Contacts()
    {
        using (var context = new ShadowContext())
        {
            return context.Contacts1.ToList();
        }
    }
}

Basic form operations. Click the delete button, set the state of the current row to deleted, save changes which marks the contact as modified and sets the isDeleted. Next remove the remove from the BindingList which in turn removes the row from the DataGridView.

public partial class Form1 : Form
{
    private BindingList<Contact1> _bindingList;
    private readonly BindingSource _bindingSource = new ();
    public Form1()
    {
        InitializeComponent();
        Shown += OnShown;
    }

    private void OnShown(object sender, EventArgs e)
    {
        _bindingList = new BindingList<Contact1>(Operations.Contacts());
        _bindingSource.DataSource = _bindingList;
        dataGridView1.DataSource = _bindingSource;
    }

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        Operations.Remove(_bindingList[_bindingSource.Position]);
        _bindingList.RemoveAt(_bindingSource.Position);
    }
}

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文