Question Retrieve a table column data using the PK of the table

andrewmanuja

Well-known member
Joined
May 30, 2019
Messages
75
Programming Experience
Beginner
Hi,

I got a table (Table1) which got few fields and among them are "costCentreID" which is the PK and the "costCentreName".

I got another table(Table2) which got some transaction related data (which got "costCentreID" as a field) and my requirement is to load the data, based on a selection criteria to a dataGridView .

However, I want to represent the "costCentreName" in the dataGridView.

What is the best method of accomplishing this task.

Can I create a function to load all the Table1 data into a DataTable() and replace all the "costCentreID" values by the "costCentreName"?

However, I am not so clear how to do the above said suggestion.

Appreciate your feedback in advance.

Thank you.

Kind regards,

Andrew
 
Look into using JOIN in the SQL query. (You could technically use Join() in the C# code, but unless you are using LINQ to SQL, you'll want to let the database do all the hard work of performing the join, instead of your users machine. Databases are specifically written to do fast joins.)
 
unless you are using LINQ to SQL, you'll want to let the database do all the hard work of performing the join
LINQ to SQL, Entity Framework, NHibernate or any other ORM is going to translate your C# code into SQL anyway. What you don't want to do is use ADO.NET to get the data separately and then use LINQ to DataSet or plain old looping to join the data in code.

This question has nothing to do with Windows Forms. Even if you were doing the join in code, that's still unrelated to your UI technology. It would be the same code in WPF or ASP.NET too.

As suggested, you would use an inner join in your SQL code to retrieve data from two related tables. Your C# will still be exactly the same, with just the CommandText of your command object changing to include the appropriate SQL, e.g.
SQL:
SELECT c.*, p.Name
FROM Child c INNER JOIN Parent p
ON c.ParentId = p.ParentId
 
Back
Top Bottom