【问题标题】:Populating Datagrid with Data from Multiple Tables使用来自多个表的数据填充 Datagrid
【发布时间】:2016-11-15 14:43:51
【问题描述】:

我需要用以下列填充数据网格。

invnumber,itemname,rate,quantity..

itemname,rate,quantity 来自一个表,而 invnumber 来自另一个表

我以前也是这样的

 string commandText = "SELECT invnumber,cname,date FROM inv_table WHERE invnumber LIKE @id";
                            SqlCommand command = new SqlCommand(commandText, conn);
                            string searchParam = String.Format("%{0}%", text_inv.Text);
                            command.Parameters.AddWithValue("@id", searchParam);


                            using (SqlDataAdapter sda = new SqlDataAdapter(command))
                            {
                                using (DataTable dt = new DataTable())
                                {
                                    sda.Fill(dt);
                                    dataGridView2.DataSource = dt;
                                }
                            }

现在我无法直接分配数据源,因为涉及到 2 个不同的表

dataGridView2.DataSource = dt;

我该如何解决这个问题。

【问题讨论】:

  • 你为什么不加入这些表?
  • @un-lucky.. 你能发个例子吗..

标签: c# sql .net datagrid


【解决方案1】:

要从一个表中的 2 个或多个不同表发出组合结果,请根据需要使用 INNER JOINLEFT JOINRIGHT JOINUNION 语句。

在这种情况下,您需要连接第一个表和其他表以获得所需的结果,假设 invnumber 是唯一的或主键。这是一个例子:

string commandText = "SELECT other.invnumber, inv.cname, inv.date FROM inv_table AS inv 
INNER JOIN other_table AS other 
ON inv.invnumber = other.invnumber 
WHERE other.invnumber LIKE @id";

或者,如果您已经为每个表定义了类,请使用带有 lambda 表达式的 LINQ to SQL:

DataContext dc = new DataContext();
var results = dc.InvTable.Join(OtherTable, inv => inv.invnumber, other => other.invnumber, (inv, other) => new { invnumber = other.invnumber, cname = inv.cname, date = inv.date });

欢迎提出任何改进和建议。

【讨论】:

  • 由于我不知道您的inv_table 上的哪个字段设计为外键,我假设您在inv_table 中有invnumber 作为other_table 主键的外键处理 INNER JOIN 中的 ON 相等语句。如果存在,请将inv_table 的外键指向other_table
  • 我已将 id 定义为两个表的主键。
  • 因此,如果两个表的 id 记录相同,则需要将 ON 子句更改为 ON inv.id = other.id。如果inv_table 上有其他字段而不是主键作为外键,请将 ON 子句更改为inv.foreignid = other.id,其中foreignid 代表other_table 上的所有相同ID。
【解决方案2】:

为 2 个不同表的数据结构创建一个新类,填充新的并使用。 (更简单,最清晰的解决方案)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多