Data grid View ( winform ) not populating properly - c#

I have two tables in my database Department and Faculty . I am populating a datagridview for department list in my winform application . Both of my tables are following
Department
Sno (int)
Name (varchar(max))
Status (bit)
Faculty_id (int)
Faculty
Sno (int)
Name
Status
Now come to code i simply drag and drop a datagridview into my form and go to code behind file . In my form's load method i write following code
var main = new SRMEntities();
var departs = main.Department.ToList();
DepartmentGrid.DataSource = departs;
now when my form load it show like this
Look in faculty column its showing nothing and when we create department we store a faculty id into department . i want to show faculty name here .
Please let me know if you have any question .
Thanks in advance
Edit
My Database Diagram

Here is correct join:
var main = new SRMEntities();
var query = from f in main.Faculty
join d in main.Department on f.Sno equals d.Faculty.Sno
select new { d.Sno, d.Name, d.Status, Faculty = f.Name };
DepartmentGrid.DataSource = query.ToList();

Everything is dependent on your query............ Your query should contain both the tables with Join.
var main = new SRMEntities();
var departs = main.Department.ToList();
DepartmentGrid.DataSource = departs;
Please check the above code "main.Department.ToList();" is returning only Departments and your assigning the "departs" to your grid.
Whether "main.Department" contains the "Faculty" table info?
By looking at your code i am guessing you have a seperate items like below
1.main.Department
2.main.Faculty

You need to join your tables
something like:
var main = new SRMEntities();
var source = (from d in main.Department
join f in main.Faculty on d.Faculty.Sno=f.Sno
select new
{
Sno = d.Sno ,
Name = d.Name,
Status = d.Status,
Faculty = f.Name
}
);
DepartmentGrid.DataSource = source.ToList();
Regards

Related

C# Linq to Entity Framework multiple unrelated queries

I have a situation where I need data from multiple database tables.
Table 1 - has list of columns which needs to be displayed on front end html, angular kendo grid - which is configurable from separate Admin configuration.
Table 2 (joining of some other tables)- has the data which needs to be displayed on the angular front end.
My linq here which I am using currently is as below.
Query 1: to get list of columns to be displayed on Grid
var columns = from cols in _context.columns
select cols.colNames;
Query 2: Get the actual data for list
var data = from cust in _context.customer
join details in _context.custDetails on cust.id equals details.custid
join o in _context.orders on cust.id equals o.custid
where cust.id == XXXX
select new Customer
{
Id = cust.Id,
Name = cust.Name,
Address = details.Address,
City = details.City,
State = details.State,
OrderDate = o.OrderDate,
Amount = o.Amount
//15 other properties similarly
};
returns IQueryable type to Kendo DataSourceRequest
Currently, From my ui I have been make two api calls one for columns and one for getting the actual data, and show/hide the columns which are configured in the columns table.
But the problem is if anyone looks at the api calls on the network or on browser tools they could see the data being returned for the columns that are to be hidden which is a security problem.
I am looking for a single query for my api which returns the data using second query which should be smart enough to send the data only for configured columns (there could be 30 different columns) and set the other properties to null or doesn't select them at all. there are some properties which needs to be returned always as they are being used for some other purpose.
I searched many resources on how could I generate dynamic linq select using the configured columns.
Please some one help me in resolving this problem
you can do something like this. Assuming you columns tables a Boolean column Display and when it is true Column will be displayed and when it is false it wont be displayed.
var columns = (from cols in _context.columns
select cols).ToList(); // note I am getting everything not just column names here...
var data = from cust in _context.customer
join details in _context.custDetails on cust.id equals details.custid
join o in _context.orders on cust.id equals o.custid
where cust.id == XXXX
select new Customer
{
Id = cust.Id,
Name = cust.Name,
Address = details.Address,
City = details.City,
State = details.State,
OrderDate = o.OrderDate,
Amount = o.Amount
//15 other properties similarly
}.ToList();
var fileterdData = from d in data
select new Customer
{
Id = DisplayColumn("ID",columns)? cust.Id:null,
Name = DisplayColumn("Name",columns)? cust.Name:null,
Address = DisplayColumn("Address",columns)? details.Address:null,
// do similarly for all other columns
}.AsQueryable(); // returns IQueryable<Customer>
private bool DisplayColumnn(string columnName,List<Columns> cols)
{
return cols.Where(x=>x.ColumnName==columnName).First().Display();
}
So now you will have this code as part of one web API call which is going to do two SQL calls one to get columns and other to get data then you will use Linq To Entity filter columns which you dont want ( or want them to null). return this filtered data back to UI.

Issue with combobox when I bind using linq join query

I am binding ComboBox using LINQ Join query. Below is my code:
var list = (from a in context.tbl_Products
join c in context.tbl_CurrentStock on a.ProductID equals c.ProductID
where c.Qty > 0
select new
{
ProductID = a.ProductID,
ProductName = a.ProductName
}).ToList();
cmbProduct.DataSource = list;
cmbProduct.ValueMember = "ProductID";
cmbProduct.DisplayMember = "ProductName";
cmbProduct.SelectedIndex = -1;
Table Details:
tbl_Products : ProductID, Product Name
Data in table
1,ABC
2,BCA
3,CDA
tbl_CurrentStock: StockID,ProductID,Qty
Data in table:
1,1,5
2,2,10
3,3,50
I am using cmbProduct.SelectedValue like below:
int ProductID = Convert.ToInt32(cmbProduct.SelectedValue);
var Product = context.tbl_Products.Single(o => o.ProductID == ProductID);
Until here it is fine. In combobox I have selected "ABC", but I am getting cmbProduct.selectedvalue value as 2 instead of 1. Same way if I select 2nd product getting value as 3 instead of 2, it is not giving selected value, instead it is giving first value in the list. What could be the problem? It's silly and eating my head. This is working fine, when I don't use JOIN Query (if I bind data from only one table)
Thanks in Advance
Problem resolved after changing sorted property of combobox to false. Combobox is sorting the productnames but not product IDs. This was causing issue. –

Linq how to move all values of two columns to another table

I want to move 2 columns of my table to an another table. I can select values that i want to move but i'am unable to move them. How can i make this ? Here is my implementation
var cartQuery = (from c in db.CartTbls.AsQueryable()
join cs in db.CartShoeTbls on c.CartID equals cs.CartID
where c.CustomerID == cusID
select new {c.CustomerID,c.TotalPrice,cs.ShoeID,cs.Quantity});
What i want to do is copy the all values of ShoeID and Quantity attiributes. Any help would be appriciated.
Use should add the selection to the table and save the changes:
foreach (var item in cartQuery)
db.OrderShoeTbl.Add(new OrderShoe()
{ ShoeID = item.ShoeID, Quantity = item.Quantity });
db.SaveChanges();
if you are using Linq to SQL, the insert is different and should look like this:
foreach (var item in cartQuery)
db.OrderShoeTbl.InsertOnSubmit(new OrderShoe()
{ ShoeID = item.ShoeID, Quantity = item.Quantity });
db.SubmitChanges();
Stefan's answer is OK however you may insert everything in one step:
var cartQuery = (from c in db.CartTbls.AsQueryable()
join cs in db.CartShoeTbls on c.CartID equals cs.CartID
where c.CustomerID == cusID
select new OrderShoeTbl{ShoeID = c.ShoeID, Quantity = c.Quantity});
db.OrderShoeTbl.InsertAllOnSubmit(cartQuery);
db.SubmitChanges();
EDIT
If you want to delete data from source table I would also wrap everything in single transaction to avoid inconsistency in case of errors.

Join data from multiple tables into SelectList, and precede each dataset with a caption in MVC

So this is a bit more complex than what I've been trying to do in the past. Essentially I have a few different tables: employee.employees, companies.employees, dbo.all_employees, and companies. They are represented by the following models, in order: employees1, employees, all_employees, and companies.
all_employees has 3 columns all_id, employee_id, and employee_type. I'm attempting to make a SelectList to populate a drop drop list, that will house all of the employees divided by their appropriate company. I've managed to get all the employees by name into the combo box, but I can't seem to figure out how separate the employees.
So think of it like this. If all_employees has a record with an employee_type of 1, they belong to our company, and their first and last name should be pulled from employees1, if they have anything other than an employee_type of 1 then they belong to another company, and should be pulled from employees
Here is my rough code that currently pulls all the employees from both tables, unions them, and places them into a select list. I simply need to figure out how to easily split them up so it looks something like
-- Select Employee --
-- Company 1
First Last
First Last
-- Company 2
First Last
-- Company 3
First Last
Code
var query1 = from c in _db.employees1
join p in _db.all_employees on c.employee_id equals p.employee_id into ps
select new { employee_id = c.employee_id, name = c.first_name + " " + c.last_name };
var query2 = from c in _db.employees
join p in _db.all_employees on c.employee_id equals p.employee_id into ps
select new { employee_id = c.employee_id, name = c.first_name + " " + c.last_name };
var merged = query2.Union(query1);
ViewBag.employeeid = new SelectList(merged, "employee_id", "name");
I have come across a possible solution in the form of a third party extension. It implements optgroup, and allows me to to easily control everything. I think this is the best solution but I'm not entirely sure.
The library is here.
And my modified code now looks similar to this:
Controller:
var query1 = from c in _db.employees1
join p in _db.all_employees on c.employee_id equals p.employee_id into ps
select new { employee_id = c.employee_id, name = c.first_name + " " + c.last_name, companyID = 1, company = "LightHouse Electric" };
var query2 = from c in _db.employees
join p in _db.all_employees on c.employee_id equals p.employee_id into ps
select new { employee_id = c.employee_id, name = c.first_name + " " + c.last_name, companyID = c.company_id, company = "Other" };
var merged = query2.Union(query1);
var data = merged.ToList().Select(t => new GroupedSelectListItem {
GroupKey = t.companyID.ToString(),
GroupName = t.company,
Text = t.name,
Value = t.employee_id.ToString()
});
ViewBag.employeeid = data;
View:
#Html.DropDownGroupListFor(model => Model.employee_id, (IEnumerable<GroupedSelectListItem>)ViewBag.employeeid,
"-- Select --", new {#data_val = "true", #data_val_required = "The Name field is required.", #class="form-control"})

asp.net Ado stored procedure fields

I have the following select in an stored procedure:
Select I.ID,
I.Name,
I.NameUrl,
I.Teaser,
I.Description,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name,
C.NameUrl,
C.Description
from Items I
inner join Categories C on C.ID=I.MainCategoryID
Some of the columns in few tables have the same name.
The asp.net ADO code below doesnt work for this equal names that im using.
My question is: Do i have to give a name, in the sql query, to the fields C.Name, C.NameUrl and C.Description in order to get it from the datatable indicated below? I Mean, i would like to avoid to put (in every stored procedure) the "C.Name as CategoryName", "C.ID as CategoryID", etc... Do you know a solution?
item.Name = Convert.ToString(dt.Rows[0]["Name"]);
item.NameUrl = Convert.ToString(dt.Rows[0]["NameUrl"]);
item.Teaser = Convert.ToString(dt.Rows[0]["Teaser"]);
item.Description = Convert.ToString(dt.Rows[0]["Description"]);
item.DateAdded = Convert.ToDateTime(dt.Rows[0]["DateAdded"]);
item.IsBanned = Convert.ToBoolean(dt.Rows[0]["Banned"]);
item.MainCategory = new Category();
item.MainCategory.ID = Convert.ToInt32(dt.Rows[0]["MainCategoryID"]);
item.MainCategory.Name = Convert.ToString(dt.Rows[0]["C.Name"]);
item.MainCategory.NameUrl= Convert.ToString(dt.Rows[0]["C.NameUrl"]);
Thanks in advance.
Regards.
Jose
You can use the column name from the result set without the qualifier.
However, you have ambiguous column names. So you need to alias them:
Select I.ID,
I.Name AS ItemName,
I.NameUrl AS ItemNameUrl,
I.Teaser,
I.Description AS ItemNDescription,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name AS CategoryName,
C.NameUrl AS CategoryNameUrl,
C.Description AS CategoryDescription
from Items I
inner join Categories C on C.ID=I.MainCategoryID
and
item.Name = Convert.ToString(dt.Rows[0]["ItemName"]);
item.NameUrl = Convert.ToString(dt.Rows[0]["ItemNameUrl"]);
item.Teaser = Convert.ToString(dt.Rows[0]["Teaser"]);
item.Description = Convert.ToString(dt.Rows[0]["ItemDescription"]);
item.DateAdded = Convert.ToDateTime(dt.Rows[0]["DateAdded"]);
item.IsBanned = Convert.ToBoolean(dt.Rows[0]["Banned"]);
item.MainCategory = new Category();
item.MainCategory.ID = Convert.ToInt32(dt.Rows[0]["MainCategoryID"]);
item.MainCategory.Name = Convert.ToString(dt.Rows[0]["C.CategoryName"]);
item.MainCategory.NameUrl= Convert.ToString(dt.Rows[0]["C.CategoryNameUrl"]);
item.MainCategory.Description= Convert.ToString(dt.Rows[0]["C.CategoryDescription"]);
...
The solution would be to refactor your database to use the right column names. Without refactoring your database, you will have to refactor your stored procedures to correctly identify the columns.
Either way, you are in for quite a bit of typing.
It will be better if you do aliasing, otherwise it will always give problem
Select I.ID,
I.Name as IName,
I.NameUrl,
I.Teaser,
I.Description as Idescription,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name as CName,
C.NameUrl,
C.Description as Cdescription from Items I
inner join Categories C on C.ID=I.MainCategoryID
Probably use an alias for the same naming column like
Select I.ID,
I.Name as itemname,
I.NameUrl as itemurl,
I.Teaser,
I.Description as itemdesc,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name as catname,
C.NameUrl as caturl,
C.Description as catdesc
from Items I inner join Categories C on C.ID=I.MainCategoryI
As a few others have said, you'll need to alias the names in your Stored Procedure and they have given you examples on how to do so. Alternatively, you can SELECT INTO a temp table and name them what you would like and then have your code pull from the temp table without any aliasing needed on the code-side. However, there is no getting around having to alias the stored procedure. Good Luck!

Categories

Resources