How do I display the value of column Department from tblDepartment to tblEmployee in a webform table? I have this code but it only displays the DeptID.
This is the Page_load code
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
DataTable dt = new DataTable();
dgvEmployee.DataSource = dsEmp.Tables["tblEmployee"];
dgvEmployee.DataBind();
These are the tables
When you need to display information from two or more different tables you can join them based on relationship(primary key and foreign key) columns:
You need to Replace this Query:
SELECT * FROM tblEmployee
With this:
SELECT employee.*,department.Department
FROM tblEmployee employee
INNER JOIN tblDepartment department ON employee.DeptID=department.DeptID
Related
I am trying to populate a combo box based off of the value member that has been selected from a data grid view.
Here is my code to initialise it
DataSet dsCIF2 = new DataSet();
DataRow drPitch;
String sqlPitch = #" Select * from Pitch";
String connStr5 = Properties.Resources.cString;
SqlDataAdapter daPitch = new SqlDataAdapter(sqlPitch, connStr5);
DataTable dtPitch = new DataTable();
daPitch.Fill(dtPitch);
daPitch.Fill(dsCIF2, "Pitch");
comboBox2.DisplayMember = "PitchDesc";
comboBox2.ValueMember = "PitchID";
comboBox2.DataSource = dtPitch;
With the following code I use this to find the ID of the pitch from the selected row on the data grid view and it returns the correct pitch ID, as seen through debugging.
int matchBookingID = 0;
matchBookingID = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
drMatchData = dsCIF.Tables["MatchStats"].Rows.Find(matchBookingID);
Pitch = Convert.ToInt32(drMatchData["PitchID"].ToString());
Now when I try to use that ID to find the datarow within the pitch table I get an error saying
Table doesn't have a primary key
on this line of code
drPitch = dsCIF2.Tables["Pitch"].Rows.Find(Pitch);
I don't know why I am getting this error, thanks in advance!
Update: The table does have a primary key
SQL CODE
create TABLE PITCH
(
PitchID int NOT NULL,
PitchDesc varchar(30) NOT NULL,
CONSTRAINT pkPitchID PRIMARY KEY(PitchID),
)
Turns out I forgot to fill the schema of the table. It works now that I have added the following line of code to the initialisation code
daPitch.FillSchema(dsCIF2, SchemaType.Source, "Pitch");
It now looks like this
DataSet dsCIF2 = new DataSet();
String sqlPitch = #" Select * from Pitch";
String connStr5 = Properties.Resources.cString;
SqlDataAdapter daPitch = new SqlDataAdapter(sqlPitch, connStr5);
SqlCommandBuilder cmdBPitch = new SqlCommandBuilder(daPitch);
daPitch.FillSchema(dsCIF2, SchemaType.Source, "Pitch");
DataTable dtPitch = new DataTable();
daPitch.Fill(dtPitch);
daPitch.Fill(dsCIF2, "Pitch");
Say if I populate a DataTable with a SQL command like this:
SQLCmd.Parameters.AddWithValue("#Date",DateTime.Today());
SQLCmd.CommandText = #"select ID, Name, Date from TestTable1 where Date=#Date";
SqlDataAdapter SQLAdapter = new SqlDataAdapter(SQLCmd);
DataTable dt = new DataTable();
SQLAdapter.Fill(dt);
Is it possible do a further query looking for something in another table which is also in dt?
For example, do something like
select ID
from TestTable2
where TestTable2.ID = dt["ID"];
Something like that... assuming both TestTable1 and TestTable2 have a column ID.
Thanks for helping!
You could use linkserver to get the data at a time or else below code may help you out. Get all the IDs with "," separated and passed it to second query.
string ids = String.Join(",", dt.AsEnumerable().Select(x => x.Field<int>("ID").ToString()).ToArray());
SQLCmd.Parameters.AddWithValue("#ID",ids);
SQLCmd.CommandText = #"select ID from TestTable2 where ID in ("+#ID+")";
SqlDataAdapter SQLAdapter = new SqlDataAdapter(SQLCmd);
DataTable dt2 = new DataTable();
SQLAdapter.Fill(dt2);
Just as an alternative option to think about, you could JOIN TestTable2 like:
SELECT t1.[ID]
,t1.[Name]
,t1.[DATE]
,t2.[ID]
FROM TestTable1 t1
INNER JOIN TestTable2 t2 ON t1.ID = t2.ID
WHERE t1.[DATE] = #Date
You can filter using DataView
DataView dv = new DataView(dt);
dv.RowFilter = "query"; // query example = "DATE = 'Your Date'"
I searched a lot but could not find the right solution.
Lets say ill select data like:
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[...]; //<== here is the problem
}
and I want to add this to a datatable,
How do I call the table in this case ?
Is it tableA ?
Does it matters how I name it ? (could I name it foobar as well???)
It is unclear what you are really asking for, but due to the length of comment and clarification, putting into an answer.
If you are trying to get multiple query results back from MySQL into a single "DataSet" (which can contain multiple tables), your query could contain multiple sql-statements and each would be returned into the dataset for you as different table results. For example, if you did something like...
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText =
#"select * from TableA;
select * from TableB;
SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
Your dataset would have 3 tables in it in direct correlation of the queries provided..
ds.Tables[0] = result of tableA all records.
ds.Tables[1] = result of tableB all records.
ds.Tables[2] = result of JOIN query tableA and tableB.
you could then refer to them locally however you need to...
ds.Tables[0].TableName = "anyLocalTableNameReference".
var t1Recs = ds.Tables[0].Rows.Count;
etc... or even create your own individual datatable variable name without having to explicitly reference the dataset and table array reference
DataTable myLocalTableA = ds.Tables[0];
DataTable myLocalTableB = ds.Tables[1];
DataTable myJoinResult = ds.Tables[2];
Hopefully this clarifies a bunch with the querying and referencing of multiple data results returned and how to then reference to the tables individually.
I've been stuck on this all day.... My love to the person who can solve it!!!!
So, there are 2 Tables
Access Table in (ds.Tables["Access"]) which contains columns of
Barcode, Description, quantity in warehouse etc
and Excel Table in (ds.Tables["Excel"]) which contains columns of
Barcode, quantiy ordered etc however named F2,F4,F8
So how do I get a final DataTable/DataSet (anything that I can .DataSource to on DataGridView) with Excel and Access matched on Barcode????
OleDbConnection conAccess = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\PROGRAMMING.LAB\\geekx_recent.mdb");
OleDbDataAdapter daAccess = new OleDbDataAdapter("Select Barcode AS BARCODE, quantity AS QTY_WH From Stock", conAccess);
DataSet dsAll = new DataSet();
daAccess.Fill(dsAll, "Access");
OleDbConnection conExcel = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\PROGRAMMING.LAB\\order.xlsx;Extended Properties = Excel 12.0 Xml");
OleDbDataAdapter daExcel = new OleDbDataAdapter("SELECT F2 AS BARCODE, F8 AS ORDER_CUST FROM [phil$] WHERE ISNUMERIC(F8)",conExcel);
daExcel.Fill(dsAll, "Excel");
DataRelation dr = dsAll.Relations.Add("Excel_Access", dsAll.Tables["Excel"].Columns["BARCODE"], dsAll.Tables["Access"].Columns["BARCODE"], false);
DataTable dtExcel = dsAll.Tables["Excel"];
DataTable dtAccess = dsAll.Tables["Access"];
DataTable dtAll = new DataTable();
var query = from ex in dtExcel.AsEnumerable()
join ac in dtAccess.AsEnumerable()
on ex.Field<string>("BARCODE") equals ac.Field<string>("BARCODE")
select new
{
Order = ex.Field<string>("ORDER_CUST"),
Stock = ac.Field<string>("QTY_WH"),
Barcode = ex.Field<string>("BARCODE")
};
foreach (var q in query)
{
dtAll.Rows.Add(q.Barcode, q.Stock, q.Order);
}
dataGridView1.DataSource = dtAll;
This returns
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.DataSetExtensions.dll
Additional information: Unable to cast object of type 'System.Double' to type 'System.String'.
At the select new block
Any ideas anyone?
See code below and following webpage for joining tables : https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
var results =
from c1 in dt1.AsEnumerable()
join c2 in dt2.AsEnumerable()
on c1.Field<int>("ID") equals c2.Field<int>("ID") into cs
select new { Category = c1.Field<string>("ColB"), Fields = cs };
I have these two tables
Table One
CODE TITLE
KANT-015 How to Build a Brand
KANT-016 Avoiding the Workforce Crisis
KANT-017 Creating Winning Social Media Strategies
KANT-028 Be Prepared to Lead
KANT-029 The Values-Based Leader
Table Two
CODE
KANT-015
KANT-016
KANT-017
KANT-028
KANT-029
How can I merge them in one dataset to dosplay them in one grid view
This is what I have done so far
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();
setOleDb = new DataSet();
OleDbDataAdapter dbaOle = new OleDbDataAdapter("SELECT * FROM tblProducts", conn);
dbaOle.Fill(setOleDb);
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(#"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
//#"SELECT C.CustomerFirstName,C.CustomerLastName,C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql);
dsSql.Merge(setOleDb);
GridView1.DataSource = dsSql;
GridView1.DataBind();
sqlCon.Close();
You're missing a PK, the merge happens on a PK.
Set one on both tables:
setOleDb.Tables[0].PrimaryKey = setOleDb.Tables[0].Columns["CODE"];