【问题标题】:Deleting from a Data Grid View从数据网格视图中删除
【发布时间】:2013-07-05 12:01:34
【问题描述】:

我创建了一个 Windows 窗体应用程序。我希望此应用程序能够使用 Linq to SQL 搜索记录,然后从数据网格视图中选择并删除该记录。

表单包含一个用于输入参数的文本框、一个搜索按钮和一个删除按钮以及一个数据网格。

我的搜索部分工作正常并且填充了数据网格,但不知道如何实现单击数据网格中的记录并将其删除。

更新 - 我已经解决了。仅对 btn_Delete_Click 事件处理程序进行了更改,因此我在主代码之后包含了他的按钮的更新代码。

namespace DeleteForm
{
public partial class Form1 : Form
{
    LinqtoStudentDataContext linqStud = new LinqtoStudentDataContext();

    public Form1()
    {
        InitializeComponent();
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {

    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        var lastName = from stud in linqStud.Students
                       where txtFind.Text == stud.LastName
                       select stud;

        dataGridView1.DataSource = lastName;
    }
}
}

更新代码 -

 private void btnDelete_Click(object sender, EventArgs e)
    {
        if (this.dataGridView1.SelectedRows.Count > 0)
        {
            dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
            //linqStud.Students.DeleteAllOnSubmit();
            linqStud.SubmitChanges();
        }
    }

【问题讨论】:

  • 从网格中获取选定的行,并按id删除学生。
  • lazyberezovsky - 我将如何处理选定的行部分?

标签: winforms linq-to-sql datagrid


【解决方案1】:

首先,将DataGridView的选择模式设置为FullRowSelect。接下来,在分配 DataSource 时,您应该调用 ToList() - 您不能使用查询作为数据源:

private void btnSearch_Click(object sender, EventArgs e)
{
    var lastName = txtFind.Text;
    var students = from stud in linqStud.Students
                   where stud.LastName == lastName
                   select stud;

    dataGridView1.DataSource = students.ToList();
}

获取选定的行,并从上下文中删除数据绑定项(学生):

private void btnDelete_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {
        var student = row.DataBoundItem as Student;
        linqStud.Students.Remove(student);
        linqStud.SaveChanges();
    }
}

【讨论】:

    猜你喜欢
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2014-07-06
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多