【问题标题】:c# remove duplicated rows in data grid viewc#删除datagridview中的重复行
【发布时间】:2015-02-11 19:32:19
【问题描述】:

我正在尝试将两个单独表中的数据显示到数据网格视图中,我知道它可能不是为此目的而设计的,尽管我确信有一种方法可以阻止它产生多个重复的行如下图;

这是获取数据的代码(我打算稍后包含过滤器或特定的搜索查询,如代码中所述,今天是今天);

private void FillPatients()
{
    SqlConnection connection = new SqlConnection();

    //DateTime timeNow = DateTime.Now;
    //string format = "MMM ddd d HH:mm yyyy";

    try
    {
        connection.ConnectionString = connectionPath;
        connection.Open();

        SqlCommand cmd = new SqlCommand("SELECT BookingId, Date, PatientId, Firstname, Surname FROM Bookings, Patients", connection);
        //cmd.Parameters.AddWithValue("@Date", timeNow.ToString(format));
        SqlDataAdapter dap = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        dap.Fill(dt);

        BindingSource bs = new BindingSource();
        bs.DataSource = dt;
        dgv.DataSource = bs;
        dap.Update(dt);

        DialogResult dlgResult;
        dlgResult = MessageBox.Show(
                "Patients loaded",
                "Patients",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information,
                MessageBoxDefaultButton.Button1);

    }
    catch (SqlException sql)
    {
        MessageBox.Show(sql.Message);
    }
    finally
    {
        connection.Close();
        connection.Dispose();
    }
}

【问题讨论】:

  • 为什么不将您的查询更改为 Select DISTINCT 还有您从中选择的第二个表在哪里......?如果这一切都存储在一个表中,那么Distinct 可以像SqlCommand cmd = new SqlCommand("SELECT Distinct BookingId, Date, PatientId, Firstname, Surname FROM Bookings, Patients", connection); 这样返回您需要的内容,您也可以进行子选择或使用 Where 子句.. 这里有很多选项
  • 好像你的 SQL 不是你想要的。也许您正在寻找 Bookings.PatientIdPatients.PatientId 上的 INNER JOIN(假设您的架构支持这个)?
  • “重复”行是什么意思?如果正在比较所有值,我在您的屏幕截图中看不到任何重复项。
  • @wgraham 我试试看
  • @AJ 其中一些记录甚至不存在于我的表格中,例如,如果有意义的话,我没有带有 PatientId 2 的 bookingId 2

标签: c# datagridview


【解决方案1】:

(从评论转换而来)

您的查询当前生成的是cross join。从本质上讲,这意味着您将从Bookings 中获取每一行,并从Patients 中获取每一行。

您可能想要的是inner join。内连接允许您为从“右”表(在本例中为 Patients)连接的记录指定谓词,因此对于每个 Booking,您可以根据外键获取与之关联的 Patient .

注意:您可以通过 WHERE 子句使用交叉连接实现相同的结果,但它已被弃用,并且根据 RDBMS,您可能会看到不同的性能。

【讨论】:

    【解决方案2】:

    我猜您需要将 SQL 更改为:

    SELECT BookingId, Date, PatientId, Firstname, Surname 
    FROM Bookings 
    INNER JOIN Patients ON Patients.PatientId = Bookings.PatientId;
    

    【讨论】:

    • Wgraham 有这个想法,R.shilling 你给了我简单的答案,谢谢大家的帮助
    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2017-08-17
    • 2016-10-02
    • 2019-02-04
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多