I would like to bind a dropdownlist with a product name and an orderItemID as its value (both from two separate tables but with relations)
Heres the database design (some columns left out for brevity)
Order - ID, Name, address
OrderItems - ID, OrderID, ProductID, Price
Products - ID, Name, description, Price
Heres the code to connect it all
var oList = ReturnOrderItems(OID).Select(pr => new {pr.Product.Name }).ToList();
DropdownListItems.DataSource = oList;
DropdownListItems.DataTextField = "NEED THE ORDER ITEM ID";
DropdownListItems.DataValueField = "Name";
DropdownListItems.DataBind();
ReturnOrderItems is a simple method to get all order items by order ID.
Then i added a Select to return the product name (as OrderItems has a relationship to the products table).
So far this works and returns the product name which is fine but how could i get the ID of the order item (which would be held inside the ReturnOrderItems(OID) method?
I've tried several ways but the most i get is productID which is no good - how should i be doing this?
Assuming that the method returns a collection ofOrderItem then you would do
var oList = ReturnOrderItems(OID).Select(pr => new {pr.Product.Name, pr.ID }).ToList();
Also are you sure you want to store the name and display the id, otherwise i think you want this:
DropdownListItems.DataTextField = "Name";
DropdownListItems.DataValueField = "ID";
Related
So I have a DGV (DataGridView) that shows a list of medication that a patient was given to. Now I am trying to show the name of the medication rather than the ID in DGV.
Picture of the DGV
I was hoping to do this with Table Views when I figured this issue but ran into another one for some reason I can't get it to write instances that only exist on the side of the linking table...
This and ER Model by VS
Picture of the part of the ER
So the result of it all is that it will write instances that should not exist and that's a problem because I am filtering the medication by the ID of the patient examination called "ID nalaza"
View data (there are 50+ instances in total)
while these 2 are the tables I am trying to connect
Tables instances
Any ideas on how to fix this issue?
You can use a DataGridView combo box to do it. You might have to adjust some of the advice below because you didn't post any code
Let's say we have Patients and Medicines and a Patient has. MedicineId for the medicine they take. In reality this would probably be a many:many relationship (many patients take same medicine, same patient takes many medicine) but DGV cannot display such, you have to repeat the rows for that, and that's a different technique - let's have a DGV that shows a patient and a medicine for now and you can expand it to show multiple rows for that patient later
So you've got your DGV showing your patient id, name, medicineid:
DGV.DataSource = context.Patients
.Where(p => p.Name == "John")
.Select(p => new PatientViewModel(p.Id, p.Name, p.MedicineId))
.ToList()
Add another column to the DGV:
var dgvcbc = new DataGridViewComboBoxColumn();
dgvcbc.HeaderText = "Medicine";
dgvcbc.DataMember = "MedicineId"; //the name of the column in the patients table
dgvcbc.ValueMember = "Val"; // the name of the property representing the medicine Id in the anonymous type below
dgvcbc.DisplayMember = "Disp"; // the name of the property in the AT below, representing the text to show in the combo
dgvcbc.DataSource = context.Medicines
.Select(m => new { Val = m.Id, Disp = m.Name } )
.ToList(); //a query that generates a key value pair into an AT for use with Display/Value newbies above
The combo will read the medicine Id from the patient and lookup the text to show. If you change the combo (select another item) the combo will push the new medicine Id into the patient list - this is a two way "binding"
I am new to LINQ to SQL and I am getting a weird result with my testing program that I don't want.
The program is a very simple WinForms app that shows SQL results in a DataGridView.
Here is my database setup.
Here is the specific column information per table.
And finally here are the results of the table shown through MSMS
Here is the issue that i'm having.
After establishing the connection to the database, I then run the following.
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.GetTable<ORDER>()
select Orders;
//select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
It returns this.
I have also tried this code
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.ORDERs
select Orders;
//select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
However the results are the same.
Then only way I can get the results i'm looking for is by doing this
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.GetTable<ORDER>()
//select Orders;
select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
Then I finally get this.
Can anyone tell me how to do a "select customers" and have it not show the column displaying "LINQ_Testing.CUSTOMER". I suspect it's because it's the foreign key causing that since it makes an EntityRef variable in the CUSTOMER class.
Try adding a virtual object of Customer class in Order class:
public virtual Customer customer { get; set; }
The foreign key relation in Order class (i.e cust_id) will lazy load the Customer object in it automatically.
First time using LinqtoSQL. So to give you guys a bit of context:
I have a simple SQL Server table called Inventory with the following fields
InventoryID (int)(autoincrementing)
InventoryItemName (varchar)(255)
InventoryCategory (int)
Next I have another table called InventoryCategories for with the following fields:
InventoryCategoryID (int)(autoincrementing)
InventoryCategoryName (varchar)(255)
InventoryCategoryDescription (varchar)(255)
Next, Currently I have a combo box which selects which query to update the DataGrid.ItemSource, The code fo for this is below
if (searchcategory == "All Stock")
{
InventoryDataContext dc = new InventoryDataContext();
var q =
from a in dc.GetTable<Inventory>()
select a;
SearchResults.ItemsSource = q;
}
Now this result returns the Full table of Inventory with the columns of InventoryID, InventoryItemName, and InventoryCategory. However it returns the ID Number of InventoryCategory, in the InventoryCategory Column.
Would anyone be able to help me get the InventoryCategoryName from InventoryCategories Table in this query instead of the ID? What would be required for this?
try using left join:
var qry = from inv in context.Inventory
from invCategory in context.InventoryCategories.Where(u => inv.InventoryCategory == u.InventoryCategoryID).DefaultIfEmpty()
select new myViewModel {id = invCategory.InventoryCategoryID, categoryName = invCategory .InventoryCategoryName }
and don't forget to create myViewModel class with id and categoryName properties
After using inner joins and fetching data from 3 tables I want to show course names that are assigned to Miss Jennifer whise Tchr_ID is 4 , ddlcourse is dropdown list id
SqlCommand cmd = new SqlCommand(#"
SELECT
Course.Course_name,
Tchr_course_ID
FROM Course
INNER JOIN CourseOffering
ON Course.Course_ID=CourseOffering.Course_ID
INNER JOIN Tchr_Course
ON Tchr_Course.Course_offer_ID=CourseOffering.Course_offer_ID
where Tchr_Course.Tchr_ID = 4", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlcourse.DataSource = dr;
ddlcourse.Items.Clear();
ddlcourse.DataTextField = "Course_name";
ddlcourse.DataValueField = "Tchr_course_ID";
ddlcourse.DataBind();
After fetching I am showing dropdown textfield as course name and I am applying datavaluefiled as tch_Course_ID because when user will select the course , its tchr_course_ID will be saved in db. to save id I am using ddlcourse.SelectedItem.Value but this gives me error in my insert statement about foreign key. It is not taking value of selected course. Why? and how can I correct it?
These tables are involved in it..
Course table:(which have courses list in it) ==>
(Course_ID,Course_name)
CourseOffering table: (which have record that these courses are
offered this semester) ==> > (Course_offer_ID, Course_ID)
Tchr_Course table: (which have record that this course is assigned to
this teacher) ==> (Tchr_course_ID, Course_offer_ID, Tchr_ID)
Profile table: (simple contains teacher record) == >
(Tchr_ID,NAme,Email)
Use SelectedValue instate of using SelectedItem.Value since ur ddlcourse has DataValueField as Tchr_course_ID hence only SelectedValue gives u required result for Tchr_course_ID.
I have a DataView object with productID and productName,
i get all items from Products Table and store them in Cache.
I want to get items that user bought in order he bought them without using another query or joining tables.
ie.
Products DataView
1. Foo
2. Foo2
3. Foo3
Filtering to ProductsBoughtByUser using RowFilter (productID in (1,3))
UserProducts DataView
1.Foo
3.Foo3
Now user first bought Foo3, how do i reorder items based on correct ( chronological ) Array. ie 3 1
Thanks
Here is the syntax for DataView.Sort:
private void SortByTwoColumns()
{
// Get the DefaultViewManager of a DataTable.
DataView view = DataTable1.DefaultView;
// By default, the first column sorted ascending.
view.Sort = "State, ZipCode DESC";
}
From your original post, it sounds like you only have Product ID and Product Name. You can't sort these in memory unless you're also retrieving a purchase/order date.
Probably the easiest thing to do would be to add the date column (PurchaseDate) to your sql statement that you're already using, then do a view.Sort = "PurchaseDate DESC";
That way, you don't have to write another statement or hit the database a second time for this sort.
Edit:
The DataRowView has integral and string indexers. e.g.:
foreach (DataRowView row in dataView)
{
var value = row["COLUMN_NAME"];
}
The column is stored as an object, so you'll have to check for null and convert to your data type