C# 将数据库中的数据检索到DataGridView C中

C# 将数据库中的数据检索到DataGridView C中,c#,sql-server,C#,Sql Server,在我的数据库类别Cat_id、Cat_name和Products中有两个表。Cat_id是Products表中的外键 当我将Products表中的产品详细信息检索到DataGridView中时,我希望通过Cat_名称而不是id本身来显示Cat_id列的值 我该怎么做?请帮帮我。下面是一个示例代码 private void searchIconPIctureBox_Click(object sender, EventArgs e) { string product_txt = se

在我的数据库类别Cat_id、Cat_name和Products中有两个表。Cat_id是Products表中的外键

当我将Products表中的产品详细信息检索到DataGridView中时,我希望通过Cat_名称而不是id本身来显示Cat_id列的值

我该怎么做?请帮帮我。下面是一个示例代码

private void searchIconPIctureBox_Click(object sender, EventArgs e)
{
        string product_txt = searchTxt.Text;

        if ((product_txt) != "")
        {
            try
            {
                conn.Open();
                com.Connection = conn;

                string search_Product = searchTxt.Text;

                com.CommandText = "select Name, Type, Amount, Price, Cat_id from Product_records where Name = search_Product ";

                SqlDataReader dtr = com.ExecuteReader();
                DataTable dttable = new DataTable();
                dttable.Load(dtr);             
                ProductGridView.DataSource = dttable;
                
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
}

SQL查询应该在产品和类别表之间使用内部联接

select Name, Type, Amount, Price, c.Name
from Personal_records
inner join Category c on records.Cat_id = c.Cat_id
where Name = search_Product

您可以使用DataGridViewComboBox来完成此操作

我从3:50开始在这段视频中这样做,但之前的视频显示了我如何进入一种情况,在这种情况下,它将创建数据集并将其放在表单上

如果你是一个读者而不是一个观察者,这里有一个文本摘要。您可能已经做了一些:

将数据集添加到项目中 将数据集连接到数据库右键单击,添加tableadapter,完成向导,完成“从产品中选择*”,对类别重复此操作 切换到表单设计器 从“视图”菜单“其他窗口”子菜单打开“数据源”窗口 将产品网格拖动到窗体中 编辑其列 将类别列从textbox更改为combobox 将其数据源设置为数据集中的categories表,将displaymember设置为name,将valuemember设置为id 运行项目
看看SQL连接能为您做些什么。我不知道为什么这会被否决;这正是Microsoft推荐的方法,因为这意味着您可以通过更改组合框来更改表ID值。。这不能通过连接查询来完成;从联接派生的绑定数据使工作变得非常困难