LINQ to SQL filter combobox output - c#

OK so I've got 2 tables for this instance, Users{UserID, Name}, Company{CompanyID, UserID, Name, Payrate}
i also have 2 combo boxes, first one is for Users which Displays Name, and the Value is UserID
i need the second combobox to get the Names from the Company table, but only showing Companies that are relevant to the selected user. I cant work out how to get it to go...
Any ideas???

What language? C#, VB.NET ? Is this a web app or Windows app? Do you have associations setup in your datacontext to link Company.UserID (child) back to Users.UserID (parent) ?

if it's asp.net and on .net 4, there's some new support for doing the filtering declaratively
if you can't or don't want to use that, then i'd make sure you're using a linqdatasource to populate and use the Selecting event on the LinqDataSource - in there, you can set e.Result to the specific linq query you want to return (against the company table, i assume), which in your case will include a 'where' for filtering to the UserID (selected value) from the other combobox

here is how you can do it.
"cbat" is the comobox
var cat = from s in db.categories select new{s.name};
this.cbcat.ItemsSource = cat.ToList();
cbcat.DisplayMemberPath = "name";
cbcat.SelectedIndex = 0;

Related

MVC: How to populate dropdownlist from sql query stored in a db field

We're using mvc to create a dynamic web form. One of the controls on the form is a dropdown. In order to populate this dynamic dropdown control, we've stored the sql statement in a single database field. It's a long story as to why we're doing it this way, but the general issue we're having is how to get our dropdown to dynamically populate using this sql field value.
For example, here's a sample record from our database. This image may be too small to read. If so, try right-clicking & opening the image in a new window (the field we're using is called "Sql"):
As you can see, we have a field called "Sql". In this record, we need to pull the "product_id" as the dropdown's id field & the "product_name" as the dropdown's text field. One known, is within the sql statement, the first field will ALWAYS be the dropdown's id. The 2nd field will ALWAYS be the dropdown's text.
And here's my dropdownlist so far:
#(Html.Kendo().DropDownList()
.Name("Filterdropdown")
.DataTextField("Text")
.DataValueField("Value")
.OptionLabel("Select")
//.Events(e => e.Change("change"))
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "",
Value = "1"
},
})
As you can see, currently, I'm not using that field to populate my dropdownlist. So my question is, how can I set this up to do so?
Thanks
According to your requirement you have to first get the query from db and than run it and with the result of this query you will bind the dropdown. Here is working code i have tried in same scenario.
Controller Code
Entities ent = new Entities();//This is my dbcontext object
//First i will query the db to get the query stored in table
Query query = ent.Queries.FirstOrDefault();
string sql = query.Query;//I have assigned the query to a string and now i will execute this
//Here i run the query in db against the table employee you need to change this to products.
var list = ent.Employees.SqlQuery(sql).ToList<Employee>();
//Create List of SelectListItem
List<SelectListItem> selectlist = new List<SelectListItem>();
foreach (Employee emp in list)
{
//Adding every record to list
selectlist.Add(new SelectListItem { Text = emp.Name, Value = emp.Id.ToString() });
}
ViewBag.SelectList = selectlist;//Assign list to ViewBag will access this in view
return View(list);
View Code
#Html.DropDownList("ddlname",(IEnumerable<SelectListItem>)ViewBag.SelectList)
Here is i have just assigned the ViewBag value to dropdown. I have not used Kendo but i hope this will help you to get on track.
Update
Instead of hitting sql server twice you can get your required data in just one query.These are two calls to sql server
Query query = ent.Queries.FirstOrDefault();
var list = ent.Employees.SqlQuery(sql).ToList<Employee>();
These two can be combined to one like this
var list = ent.Employees.SqlQuery(ent.Queries.FirstOrDefault().Query).ToList<Employee>();
Here I understand that you are trying to populate a dropdown with some data. But, I am not sure of the reason why you are saving SQL query in a DB table. Possible reasons could be that the query to extract data for your dropdown is not always the same and you want that flexibility to modify the query through DB. Though this may not be the best of appraoches to achieve your requirement, hope it serves your purpose for now.
Now, coming to your requirement of extracting data for a dropdown, you could have easily achieved that through a simple subquery/function if you were using ADO.NET with SQL for querying. But, here as your application is build on MVC, you might be using Entity framework for data access which makes you think of only LINQ for querying.
Fortunately, though LINQ is the only direct way of querying DB entities via Entity Framework, you can also execute raw SQL queries through LINQ.! So, all you need to do here is:
Step 1) Get the SQL query stored in DB using LINQ.
sql = DbContextObj.YourQueryTable.ConditionToGetQuery..();
Step 2) Execute the query obtained in step 1 using .SqlQuery(sql) method on your data entity:
DataForDropDown = DbContextObj.YourDataTable.SqlQuery(sql).ToList..();
Now, you can use a HTML helper to generate a Dropdown control binded with your data.

Display data from many to many relationship in windows form using LINQ

I have three tables stored in my database: Speaker, Language, and link_speaks. All three of them have multiple attributes. link_speaks is used to connect the Speaker to Language "many to many" - relationship. The primary/foreign key relations are defined in the sql database.
Table information:
I would like a windows form to display the information in Speaker for every entry plus a table of the languages he/she speaks, taken from the other two tables.
The result would look a lot like this (taken from this tutorial I found)
How can I achieve this?
Set the binding navigator on the main page to have the datasource as the entire tbl_Personen.
Then set the bindingsource on the datagridview to that person objects related person's language...
Here's some kinda code to do the first part (it's not perfect, but you get the general idea):
using (var data = yourdataentities())
{
var person = data.Personen.FirstOrDefault();
formbindingsource.DataSource = person;
var languagesGuySpeaks = from p_x_l in data.link_spricht
join language in data.Sprachen on language.Id equals p_x_l.SprachID
where p_x_l.Person_ID == person.Id
select language;
datagridbindingsource.DataSource = languagesGuySpeaks;
}
Then add an event handler to update datagridbindingsource.DataSource when your person changes (however you want to handle that; like a dropdown or whatever)

linq to sql update mulitple rows

I am trying to update a sql table using linq to sql :
Querying the database using Linq to SQL I am able to load the data into a gridview in the UI in a WPF application. So I have a check box associated with each row. The table has EmpName and Ability as two columns. So when user checks the check box associated with the row/rows I have to update the value in the table back in the sql DB.
Here is the code for my check box checked :
private void EmployeeName_Checked(object sender, RoutedEventArgs e)
{
DataDataContext dc = new DataDataContext();
foreach (var item in empListView.SelectedItems)
{
EmpList updateList = (from p in dc. EmpList
where p.able == No
select p).FirstOrDefault();
if(updateList.able==NO)
updateList.able = YES;
}
dc.SubmitChanges();
empListView.ItemsSource = dc.EmpLists.ToList();
}
EmpList here is the one created when I added the linqtosql class from the designer. So I am trying to update the same list which inturn submits the changes to the DB.
Question: I am able to select the rows based on the selected checkboxes in the gridview and I am able to loop through the selected items, but I am unable to update all the selected rows..only few are updating...I would be glad if some one can look at the code and guide me if theres any thing wrong with the query.
Ultimately, I have to update all the selcted rows based on their current values in the colum Ability of the gridview.
Here is a good article on Batch Updates and Deletes with LINQ to SQL
http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx
Maybe this gives you an idea or a pointer...
DataDataContext dc = new DataDataContext(); needs to be moved outside of the foreach loop. Currently it should not compile because it is out of scope. I don't understand how you are linking the item selected to the item you are pulling from the data set, you are just pulling the first one? Does your item have an Id or something to grab?

Comparing two datasources in C#

I have a gridview, bound to a datasource whose database table contains a foreign key that is associated with the database table that is used as the datasource for a dropdownlist.
What I want to do is if a certain foreignKeyId exists in gridview.datasource, to remove it from dropdownlist.datasource.
To give a clearer idea of what/why I want what I want, the user is able to add entries to the gridview (and therefore the datasource), but I don't want the user to be able to make more than one entry for a specific type. Is there a way that a linq query could do this?
pseudocode (note that I know RemoveObjects() is an invalid method)
var query = DataContext.Items.Where(item => item.TypeId == selectedTypeId);
dropDownList.DataSource.RemoveObjects(query);
Here is how I bind the dropdownlist, so maybe I could do something here to not get the items with already existing TypeId's?
dropDownList.DataSource = DataContext.Items.Select(items => new
{
items.Name,
items.TypeId,
}).ToList();
Any suggestions or answers would be great!
Have you tried using except
dropDownList.DataSource.Except(query)

LINQ to SQL, anonymous types are read-only

I'm using LINQ to SQL and DataGridViews to create an editable user interface of a database.
My problem is that I have to translate the column names when fetching the results from the database, because while all names in the database are in English (the only language supported by the visual studio class designer) I have to display them in a different language...
So I thought about using anonymous types:
c_dgvShops.DataSource = (from Shop s in DataContext.Shops
select new
{
Azonosito = s.Shop_ID,
Nev = s.Name,
Megye = s.County,
Iranyitoszam = s.Zipcode,
Cim = s.Address,
Latogatasok_szama = s.Visits.Count
});
(Please note that the property names of the anonymous type are in Hungarian [the language I have to display in], translated from English.)
This resulted in the DataGridViews being read-only.
I made some Google searches, and found this:
http://blogs.msdn.com/swiss_dpe_team/archive/2008/01/25/using-your-own-defined-type-in-a-linq-query-expression.aspx.
Based on this article, I created a new class called 'Bolt' (Hungarian equivalent for Shop) and filled it with the translated property names, so the query became:
c_dgvShops.DataSource = (from Shop s in DataContext.Shops
select new Bolt
{
Azonosito = s.Shop_ID,
Nev = s.Name,
Megye = s.County,
Iranyitoszam = s.Zipcode,
Cim = s.Address,
Latogatasok_szama = s.Visits.Count()
});
Although it's not totally clear to me, how would this make it possible to edit the data displayed in the DataGridView, I tried it, and got an exception:
NotSupportedException: Explicit construction of entity type 'DataTest_L2SQL.Bolt' in query is not allowed.
So what's the correct way of doing this? How can I display alias column names, but still keep the data editable?
Thank you very much in advance!
You should be manually defining the datagrid columns (which would allow you to set their caption to anything you want as well as customize the size and display formatting), not relying on the datagrid to discover your columns through the data source - this feature is only meant for quick and dirty setups.
You are going about it the wrong way. You shouldn't be using different class property names for localization.
Follow this guide to localize your page. Specify the HeaderText for the column, change the form language and then re-specify the HeaderText for the language.

Categories