How to display values into gridview from sql databese - c#

In my database i have three tables. One For employs where i keep their names, ids, salary... In the second one named Project i keep id, location, name. in the third one named WorksOn i keep the id from employs and the id from project. In my Asp .Net web site in gridview i need to display the employee's name and the name of the project that he is working.
string connect =
WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(connect);
try
{
con.Open();
}
catch (Exception err)
{
string error = err.Message;
con.Close();
}
SqlCommand command = new SqlCommand();
command.Connection = con;
SqlDataReader reader;
command.CommandText = "SELECT * FROM WorksON ";
reader= command.ExecuteReader();
In data source in gridview if i choose to display the values from WorksOn table it shows the id from employs and the id from project but what i need is to show the names on the employs and project.
I know that i need to do something with dataset but i don't know who.

Your SQL command must JOIN the related tables. Something like:
SELECT * FROM WorksOn JOIN Employee on WorksOn.EmployeeId = Employee.Id
Note that you should not SELECT "*" (all columns). You should only SELECT those columns that are necessary to your data view for performance.

On your SQL command, you don't mention anything about Employs. You need to use a JOIN SQL command in order to get both the employee name and the company name.
And instead of using "SELECT * FROM...", consider using the columns name instead, because you're not trying to get all the columns display. And it will help us understand the name of the columns to further help you.

Use a JOIN query like this:
SELECT project.projectName, employee.Name
FROM (worksOn
INNER JOIN employee
ON (worksOn.employeeId = employee.employeeId))
INNER JOIN project
ON (project.projectId = employee.employeeId)
AND (worksOn.projectId = project.projectId)

Related

How to show different data to different users?

Lets say parents have logged into system, and I would like to show them only their children details in GridView control. Up to one child can be studying at the same school. How can I achieve that? I've tried to join 3 tables in my database and display into GridView like this:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source = DESKTOP-H7KQUT1; Initial Catalog = SAOS; Integrated Security = True");
String query = "SELECT s.FName FROM student s INNER JOIN student_parent sp ON s.SID = sp.SID INNER JOIN parent p ON sp.PID = p.PID WHERE p.PID = ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
I can display student details successfully but I don't know how to display different student details to different parents. I stuck at this line:
String query = "SELECT s.FName FROM student s INNER JOIN student_parent sp ON s.SID = sp.SID INNER JOIN parent p ON sp.PID = p.PID WHERE p.PID = ";
Any Advises & References are appreciated
If I'm understanding your schema, it looks like you've mostly got it: you need to get the parent id (pid) by looking at which user has logged into your web app. Then you would use that information to most likely execute a query to lookup the pid. Then you pass that as a parameter to your SQL statement in the form 'where p.pid=#PID'. Here's some documentation on how to construct a query with parameters: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.7.2
Just one word of warning: be very careful about how you get and verify the parent id (i.e. don't just pass it in as a URL parameter, make sure it's something you authenticate and keep on the server side so it can't easily subject you to spoofing and injection attacks)

Join Query in ACCESDB giving a IndexOutOfRangeException error

I'm sure all table names are ok. I want to get the list of players of each team.
public List<Speler> getSpelersPerPloeg(int ploegID)
{
List<Speler> spelersLijst = new List<Speler>();
connection.Open();
OleDbCommand command = new OleDbCommand("select * from proj1Speler inner join proj1Ploeg on proj1Speler.ploegID = proj1Ploeg.ploegID where proj1Ploeg.ploegID = #ploegID", connection);
command.Parameters.Add(new OleDbParameter("#ploegID", ploegID));
OleDbDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
spelersLijst.Add(new Speler((int)dataReader["spelerID"], dataReader["spelerNaam"].ToString(), (int)dataReader["ploegID"], dataReader["ploegNaam"].ToString(), (int)dataReader["spelerTypeID"]));
}
dataReader.Close();
connection.Close();
return spelersLijst;
}
It trows the error with ploegID on this line " spelersLijst.Add(new Speler((...", any ideas?
And the funny thing is with sql server it works without any problem, maybe my relations in Acces are wrong?
You are joining the two tables using the *, in this way fields from both tables are returned from your query.
But what happens when you have two fields with the same name from the two different tables in the same query? Some automatic renaming occurs, the tablename is added to the two identical field names to disambiguate the column name.
So when you try to use the simple name (without the table name) you get the error. I bet that the culprit is the "ploegID" field that appears in both tables.
I suggest to return just the field names really required by your code
OleDbCommand command = new OleDbCommand(#"select ps.spelerID, ps.spelerNaam,
pp.ploegID, pp.ploegNaam, ps.spelerTypeID
from proj1Speler ps
inner join proj1Ploeg pp
on ps.ploegID = pp.ploegID
where pp.ploegID = #ploegID", connection);
command.Parameters.Add(new OleDbParameter("#ploegID", ploegID));
OleDbDataReader dataReader = command.ExecuteReader();
(Note, I am not really sure about what field is contained in which table, this is just to get the idea)

Referencing a control from SQL query

I'm using C# to link with an Access database I have. I added this database by using the Data Source Configuration Wizard in VS, and now there are a couple of queries I'm trying to run.
This is the query I'm having trouble with, I think it's having an issue with me trying to reference a combobox from inside the query.
SELECT DISTINCT Column2
FROM MyTable
WHERE Column1 = cboMyComboBox.Text
ORDER BY Column2
A sample of data in the MyTable
Column1 Column2
Male Bob
Female Jane
Male Jim
Male John
Female Jill
And lets say the value in cboMyComboBox is 'Male'
I'm trying to get the query to return 'Bob', 'Jim' and 'John'
I'm pretty new to this so I'm probably missing something completely obvious, and feel free to refer me to any guides on doing this properly. (It may have something to do with parameters...? Do i need to be passing something to this query?)
The error I'm receiving is "No value given for one or more required parameters"
string query = String.Format(
#"SELECT DISTINCT Column2 FROM MyTable
WHERE Column1 = '{0}' ORDER Y Column2", cboMyComboBox.Text);
Otherwise the sql query will try and literally match column1 to the string cboMyComboBox.Text as opposed to the data in it.
In complete form:
public DataTable dattab;
public void GetData()
{
//setup the parameters for connecting
string connString = #"";// You need to define you connection string here.
string query = String.Format(#"SELECT DISTINCT Column2 FROM MyTable WHERE Column1 = '{0}' ORDER Y Column2", cboMyComboBox.Text);
//Create the connection and commmand objects, then open a connection to the DB.
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
//Retrieve the data and fill the datatable
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dattab);
//Close off connections
conn.Close();
da.Dispose();
}
Figured it out - In the query properties there is an option to add parameters - I was able to add it here then pass the combobox value when i ran the query method:
tableAdapter.GetColumn1Data(cboMyComboBox.Text)

How to populate database information from dropdown selection?

I have a students table, a courses table and a student/courses table to show the students enrolled in a course. The table is in SQL Server 2008 and the front end in C# and Asp.net.
In the student/courses table I would like to be able to have a dropdown menu that will allow me to select the student ID stored on the database and then populate the student's name, last name and middle initial in a textbox or label.
How can I possibly do this? Any examples? Thank you for your help!
You can use either ADO.net, if not familiar then
on page load event
SqlCommand cmd = new SqlCommand();
cmd.Connection= new Class1().getconnection();
cmd.CommandText = "SELECT * FROM Profile";
cmd.Connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr["YahooId"].ToString());
}
in "cmd.CommandText" instead of "Profile" use your table name, and under "while(dr.read()) use your column name instead of "YahooId"

Need some help working with databases in C#

I have a database with two tables. Both of these tables are related and have the same key field. For example, both of them have rows of data corresponding to ISBN = 12345, but the two tables have differing data about that ISBN.
So, I'm trying to figure out how to display data from both tables into one dataGridView. I have tried some SQL commands I found online, but it looks like commands in C# might differ from normal SQL queries.
Suppose table1 has these fields: ISBN, color, size and table2 has the fields ISBN, weight.
I need a way to display ISBN, color, size, weight in my datagrid view. I think I will have to somehow do this with an adapter. I am able to connect and do queries on the tables individually, and show that data in my datagridview, but I can't figure out how to mix data from two separate tables.
If you have a good resource I can read about this I'd love to have it, my google-fu is failing me.
Here's an example of something I can do now with my database:
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.Book' table. You can move, or remove it, as needed.
this.bookTableAdapter.Fill(this.database1DataSet.Book);
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + #"C:\Users\Geoff\Documents\cs 351\Database1.accdb" + ";Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(connectionString);
string query = "select * from Book where ISBN = 12345";
OleDbCommand com = conn.CreateCommand();
com.CommandText = query;
OleDbDataAdapter adapter = new OleDbDataAdapter(com);
DataSet data = new DataSet();
conn.Open();
adapter.Fill(data);
conn.Close();
dataGridView1.DataSource = data.Tables[0];
}
So, essentially, I'd like to do what I've done above, but I want to include the data from a different table too. The other table also has a key field ISBN, and it contains values of ISBN that match the first table.
Look into the use of JOIN to return the results from two tables JOINed together ON some common value
See Also
Wikpedia: Join
(SQL)
W3Schools: SQL
Joins
SQL-tutorial.net: SQL
Join
SO: SQL JOIN ON vs WHERE
Coding Horror: visual explanation of SQL JOINs
There's nothing limiting this to C# or OLEDB -- it's basic SQL.
For the specifics of what you're asking a query might look like the following:
SELECT T1.ISBN, T1.color, T1.size, T2.weight
FROM table1 T1
INNER JOIN table2 T2
ON T1.ISBN = T2.ISBN
WHERE ISBN = '12345';
(There's no need to alias table1 as T1 -- I just did that as an example; in more complicated queries with longer table names, you might not want to repeat the table name all the time)
since ISBN occurs in both tables, it must be explicitly qualified in your field-selections; either T1 or T2 can be used, as they are identical
since color, size and weight each occur in only one table, they do NOT need to be qualified -- but it doesn't hurt.
var query = "SELECT t1.isbn, t1.color, t1.size, t2.weight FROM table1 t1 JOIN table2 t2 ON t2.isbn = t1.isbn";
var connection = new System.Data.SqlClient.SqlConnection("your SQL connection string here");
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(query, connection);
var dataSet = new System.Data.DataSet();
dataAdapter.Fill(dataSet);
yourGridView.DataSource = dataSet;
yourGridView.DataBind();
This is one of many solutions. I think the code might be faster if you create an in-memory DataTable and use an SqlDataReader, but the sample above is simpler.
When working with MSSQL databases, you normally use the System.Data.SqlClient classes. If you - for whatever reason - use OleDb, pick the corresponding objects from the System.Data.OleDb namespace.
You can query records from both tables using UNION ALL
SELECT 'In table 1', book_author, book_title, book_isbn
FROM books
WHERE book_isbn = '67890'
UNION ALL
SELECT 'In table 2', othertable_author, othertable_title, othertable_isbn
FROM othertable
WHERE othertable_isbn = '67890'
of course you'll need to manually fill the '67890' in both places using whatever method is more convenient in your situation.

Categories

Resources