mike22
New member
- Joined
- Aug 21, 2017
- Messages
- 2
- Programming Experience
- Beginner
I have some code for listing product names and corresponding categories, by using Data Sets :
So at the end i should have results on console, i assuming that maybe i could use for each (or not?) , need help about it..
my code bellow:
Thanks in advance and happy programming
- created the Connection, Data Adapter, and Data Set
- Filling the Data Set with the Categories table
- Changed the command text and retrieve the Products table
- Defining the relationship between Categories and Products
- Adding the relationship to the Data Set
So at the end i should have results on console, i assuming that maybe i could use for each (or not?) , need help about it..
my code bellow:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using.System.Data.Common;
namespace consoleAsgDatAccess
{
class Program
{
static void Main(string[] args)
{
// Create the Connection, DataAdapter, and DataSet.
string connectionString = "Data Source=localhost;Initial Catalog=NORTHWND;" + "Integrated Security=true";
SqlConnection con = new SqlConnection(connectionString);
string sqlCat = "SELECT CategoryID, CategoryName FROM Categories";
string sqlProd = "SELECT ProductName, CategoryID FROM Products";
SqlDataAdapter da = new SqlDataAdapter(sqlCat, con);
DataSet ds = new DataSet();
try
{
con.Open();
//Filling tge DataSet with the Categories table.
da.Fill(ds, "Categories");
//Changing the command text and retrieve the Products table.
// Oprional using another DataAdapterr object for this task.
da.SelectCommand.CommandText = sqlProd;
da.Fill(ds, "Products");
}
finally
{
con.Close();
}
//Defining the relationship beetween Categories and Products.
DataRelation relat = new DataRelation("CatProds",
ds.Tables["Categories"].Columns["CategoryID"],
ds.Tables["Products"].Columns["CategoryID"]);
//Adding the relationship to the DataSet.
ds.Relations.Add(relat);
}
}
}