【发布时间】: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.PatientId到Patients.PatientId上的INNER JOIN(假设您的架构支持这个)? -
“重复”行是什么意思?如果正在比较所有值,我在您的屏幕截图中看不到任何重复项。
-
@wgraham 我试试看
-
@AJ 其中一些记录甚至不存在于我的表格中,例如,如果有意义的话,我没有带有 PatientId 2 的 bookingId 2
标签: c# datagridview