Updating Data with LINQ and BindingSource - c#

I am writing a relatively simple Windows Form app that is supposed to act as a front-end (adding, editing, removing entries) for a SQL Server database we have. I have a TextBox for each column in the table, and a ListBox to list all the entries (by first and last name). The TextBoxes get populated with the data of whichever entry is selected in the ListBox.
I am having some difficulty updating entries in the DB using the BindingSource. Here is the code that I am currently (unsuccessfully) using:
DBDataContext dc = new DBDataContext();
Entrys e = (Entry)EntryBindingSource.Current;
dc.Entrys.Attach(e);
dc.Entrys.InsertOnSubmit(e);
dc.SubmitChanges();
With this code I get an exception that the entry already exists, which makes sense, but I don't know how to tell it that I want to update that entry with the new data.
I know how you can manually update each entry, but since I have 10 different columns, that would be a relatively large if/else tree (checking if each textbox's value is different than the BindingSource's value for that entry). Deleting and then re-adding that entry just seems like bad form to me. I'm sure there's a better way of doing it.

I highly doubt you are doing this right.
Using Linq you should first try to retrieve your entry/check for its existence, then make your changes, and then only submit them. Updating this way should be pretty straightforward. the "InsertOnSubmit" call is in my opinion very suspicious.

Related

Why does updating gridview also update the datasource (datatable)? If its 2 way then which is better for iteration?

I have a datatable in code. And the datagridview in the Ui.
In code I have done gridviewName.DataSource = dtTable1
Now in the UI I can see gridview populated with the table data. In the UI gridview I can update the cell values and/or delete the data rows. Upon doing any changes to the gridview, the changes automatically flow back into the data table.
I am bit confused at this point because I had thought it is a 1 way connection from data table into datagridview. Is this 2 way by design? If yes, then subsequently if I want to perform an operation per row, like send an email per row, then it is recommended to iterate over the gridview or the data table?
Yes, the 2 way data flow is by design; it makes creating applications a lot easier. If you don't want your user to edit a grid you make the grid read only, but typically you show data to a user, you let them edit it and save it. That would get a lot more hard work if you made data binding a one way thing the grid is connected to the datatable directly; it doesn't copy the data it finds into its own internal data array
Always loop over the datatable, read it and edit it directly; the grid will update accordingly; always avoid looping over the datagridview. As the embodiment of model-View-controller your code should manipulate the model (datatable) not try and manipulate the model via the view/controller that is intended for the user (the datagridview)
If you add a DataSet type file to your project and design a strongly typed datatable inside it your life gets easier. Your code looks like:
foreach(var r in soneDataset.EmailQueueDataTable){
mailer.Send(r.From, r.To, r.Subject, r.Message, r.RetryAttempts);
}
With a standard datatable everything is done with string column names or worse, ordinal positions and needs casting:
foreach(DataRow r in EmailQueueDataTable.Rows){
mailer.Send((string)r["From"], (string)r["To"], (string)r["Sujbect"], (string)r["Message"], (int)r["RetryAttempts"]);
}
Intellisense won't help you with the column names either; you'll only find out at runtime that I made a typo in Subject

How do I set the content of a label to a database table cell in WPF?

I have built a program in WPF using Visual Basic that allows users to select from a series of items. The list of items may change as I add more items or remove older ones. Originally, I would just add and remove these items in the project code, and rebuild the executable.
Over time, however, the list of items grew and became tedious and impractical to maintain in the code. It occurred to me that it would be easier to store the items in a database table which the program can read, and the list can just be updated by adding and removing items from this database.
I have the database built, and I've added it as a Data Source. I have the data connection set up and everything is ready to go.
What I need to know is how to set the Content property of a label to a cell from a table in the database. I want to do this in the codebehind, not in markup (XAML).
My guess is that I will need to set up a sort of query with a for loop to find the cell I want.
The name of the database is ItemsDB. It contains a table called ItemsTable, and the fields in the table have a unique ID (key) with an AutoNumber data type. The column containing the data I want is named ItemLabel.
So, to sum it all up, I want a label to show the content from a single cell in the database, specified in the codebehind. Either C# or VB is fine.
EDIT
I guess I should've mentioned that the labels themselves actually function as buttons, and I don't really want to display a ListView if I don't have to. I know it's not helpful to not have any code posted, but I don't even know where to start, so there's no code to post.
Took a while longer than I expected, hope this is still useful. So, what you want to do is iterate through a collection and create a new Label for each row.
You will need a container for the Labels, I used WrapPanel, but you can use any Panel you want. I'm replacing your Data Source with a simple DataTable, you'll get the point from this:
foreach (DataRow row in YourItemsTable.Rows)
{
Label newLabel = new Label();
newLabel.Content = row["ItemLabel"].ToString();
// If you need some events, attach the handlers here
yourParentContainerPanel.Children.Add(newLabel);
}
This should be all you need.

C# : Resetting DataGridView for new DataTable

Ok so I'm trying to make a simple SQL CE Viewer application just to view my local databases for another application, I have it setup so that I can select what database I want to open and then it automatically populates a combo box with all of the tables in the database. When I select a table it populates a DataGridView with the records in the table.
My problem is switching between tables. I can't seem to get the DataGridView to remove everything from the previous table and re-populate the DataGridView with the new table information. Of course each table has different columns and rows and such.
I've googled and searched on here and every suggestion I find doesn't seem to work. It populates the DataGridView with the first table just fine, but when I select another it basically adds the columns and rows into whatever was there....
How can I get the DataGridView to completely clear for new data?
And please don't tell me to use dataGridView1.DataSource = null; tried that, doesn't work.
Well, I checked it in one of my programs and just changing DataSource property is working fine. I didn't have to use datagridview.Refresh(). Maybe it depends on the kind of DataSource, which you are using to set datagridview data?
Write this line after you have done populating the DataSource with the new data
dataGridView1.Refresh();
You don't need to clear the DataGridView directly. Its always handled by modifying the DataSource of the DataGridView.
If there is nothing else in the form, you can simply call InitializeComponent() again. But I think #Josh is right.

DataGridView binding after replacing column with comboboxcolumn

I'm in C# Express 2010 and SQL Server Express 2008, making a winforms front end for simple table editing. User picks a table from a combobox, and a datagridview is populated with that table. There's a Submit and Reload button at the bottom of the form. It's loosely based on Microsoft's example for binding a DGV to a database.
So, I have this datagridview that is populated by a data adaptor. After it's been populated, I go through the resulting table and replace any columns with foreign keys with comboboxcolumns so it's easier for the user.
This bit all works fine. The comboboxcolumn shows up, with the correct data in it etc etc. I've set the Headertext, DataProprtyName, and Name properties to match the column it has replaced.
It DOES seem to have broken my 'submit' button that does the update command. Basically, if I change the value in one of the comboboxcolumns, I get a concurrency violation. If I change a value in any other column, it silently fails (when the data is reloaded into the DGV, the updated value vanishes).
Any ideas what the problem could be here?
If you need to see code just let me know. There's rather a lot of it as I'm a newbie and have probably done things in a horrendously messy way!
Thanks in advance.
Never mind - I figured it out - I had copy/pasted a procedure and forgotten to create a new DataAdaptor, so it was using the same one as the one used to populate the DGV, hence things went A over T...

How to filter the following listboxes in asp.net?

I have 4 listboxes (lstStates, lstCounties, lstCities, and lstZipcodes). Here are a few constraints:
None of the listboxes are disabled.
Any listbox can be selected at anytime, meaning there is no specific order the user has to choose.
Filtering is forward and backwards. By this, I mean if a user selects a state from lstStates, it will filter lstCounties, lstCities, and lstZipcodes. If a user selects a zipcode from lstZipcodes, it will filter lstCities, lstCounties, and lstStates.
The listboxes allow multiple selections.
Each listbox is bound to a datatable to get its initial data. The datatable is retrieved from a sqlserver stored procedure. Each listbox has its own stored procedure, for example, lstStates has one called GetStates which returns one column (State) and the ListBoxes DataValueField and DataTextField are both set to State. Similar to lstStates, lstCities is bound to a datatable which gets one column from a GetCities stored proc which is city.
Another thing I want to point out is that I am connecting an ObjectDataSource to get the datatable.
Already been asked: What is the most efficient way to filter listboxes based on selections of another in c#?
[edit]
OK, what you need to do is add an event to each [myListbox]_SelectedIndexChanged event. When the selection is changed you'll need to refresh all the other listboxes based on those selections. I assume that this will need to be handled by the database, since linking States to ZipCodes any other way would be ugly. So presumably your data for States<-->Zips<-->Counties relationships is in your db somewhere.
So you'll need to have procs in your db (or LINQ middle layer) that get States by Zips and so on. On each selection changed event, send the new selection back to the db sproc and then rebind the listbox based on the return data. You should be able to make one sproc for each one that returns all states if no zip is passed in and so on.
[/edit]
To clarify, on your initial load of the page, you are loading ALL zipcodes, ALL cities, ALL states and ALL countries?
This seems a bit cumbersome to me. This is the type of requirement I would question. (Granted I don't know that you didn't already question it or that some good answer came from it).
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "bab", "CacheItems();", true);
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {
ddlText = new Array();
ddlValue = new Array();
ddl = document.getElementById("");
for (var i = 0; i

Categories