linq to sql update mulitple rows - c#

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?

Related

C# visual studio using AddtableRow to add rows to a table and am getting an overload error but the field count is correct

In this system one program creates table records and a second updates them. I want the update program to see the new records. See lots of queries/responses to this but so far none have worked for me. One solution was to clear and reload the dataset table. The following code recreates the dataset but I can't include the auto incremented primary key bookid. If it is there I get an overload error even thought the field count is correct. If I remove it the dataset.booking table is loaded but the bookid values are wrong negative numbers) and I can't update the dataset.booking table as it does not match the database table.
tclDataSet3.booking.AcceptChanges();
tclDataSet3.booking.Clear();
bookingBindingSource.ResetBindings(false);
dataGridView1.ClearSelection();
var bkas1 = tcdb.bookings.Where(b => b.approvalStatus == 1);
foreach (booking bk in bkas1)
tclDataSet3.booking.AddbookingRow(
(int)bk.bookId,
(int)bk.bookYear,
(int)bk.bookMonth,
(int)bk.bookDay,
(int)bk.workOrder,
(int)bk.customerNum,
bk.firstName,
bk.lastName,
bk.vehicle,
(int)bk.serviceCar,
bk.repairType,
(bool)bk.isCompleted,
(bool)bk.isPickedUp,
bk.outYear,
bk.outMonth,
bk.outDay,
(bool)bk.isDeleted,
(int)bk.isUpdated,
bk.bookingTime,
(int)bk.approvalStatus);
Program requirements:
display datagridview of dataset.booking table where as_code = 1
updates rows in datagrideview to change as_code = 2
remove updated rows from datagridview (bookingBindingSource.RemoveCurrent(); works well)
Refresh datagridview to see all dataset.booking table rows where as_code = 1
Currently the refresh only sees existing records in the datagrideview.
Is there a better way to do this?
After much trial and error I decided to rewrite the code to manually build the dataGridView rather than use any data binding. I created a subroutine to clear the dataGridView, read the base table and rebuild the dataGridView.

empty a specific column of numbers from the datagridview

Question:
How to empty specific column of numbers from datagridview? (i mean erase the values without header, not delete the column).
for example FROM THIS TO THAT, so i dont need to do it manually
How i created the datagridview:
i created a database table, with 5 ID's all of datatype "int", i connected the datagridview through DataSource, bindingsource. And when i put values in the table and press button:(button code below)
table1BindingSource2.EndEdit();
table1TableAdapter2.Update(database1DataSet8.Table1;
It will save the values into DataTable.
For example the first ID in the table is : Konduktivita1[µS_cm-1]
What i think is neccesery is to actually delete the values from DataTable but i dont how to do it.
It would be easier if you provided some kind of code, but let's try something like this.
var sourceList = dataGridName.ItemsSource as List<sqlTable>; //or whatever your data is called
foreach (var item in sourceList)
{
item.Konduktiva1 = null; // or 0
}

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.

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 filter combobox output

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;

Categories