Updating a Database from DataBound Controls - vb.net

I'm currently creating a WinForm in VB.NET bound to an access database.
Basically what i have are two forms: one is a search form used to search the database, and the other is a details form. You run a search on the searchForm and it returns a list of Primary Keys and a few other identifying values. You then double click on the entry you want to view, and it loads the details form.
The Details form has a collection of databound controls to display the data: mostly text boxes and checkboxs. The way i've set it up is i used the UI to build the form and then set the DataBindings Property of each control to "TblPropertiesBindingSource - " where value name is one of the values in the table (such as PropertyID or HasWoodFloor).
Then, when you double click an entry in the searchform, I handle the event by parsing the Primary Key (PropertyID) out of the selected row and then storing this to the details form:
Note: Detail is the details form that is opened to display the info
Private Sub propView_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles propView.CellDoubleClick
Dim detail As frmPropertiesDetail = New frmPropertiesDetail
detail.id = propView.Rows(e.RowIndex).Cells(0).Value
detail.Show()
End Sub
Then, upon loading the details form, it set's the filter on the BindSource as such:
TblPropertiesBindingSource.Filter() = "PropertyID=" & id
This works great so far. All the controls on the details form will display the correct info. The problem is updating changes.
Scenario:
If i have the user load the details for say, property 10001, it will show a description in a textBox named descriptionBox which is identical to the value of the description value of for that entry in the database. I want the user to then be able to change the text of the text box (which they can currently do) and click the save button (saveBut) and have the form update all the values in the controls to the database.
Theorectically, it should do this as the controls are DataBound, thus i can avoid writing code that tells each entry in the database row to take the value of the aligned control.
I've tried calleding PropertiesTableAdapter.Update(PropertiesBindingSource.DataSource), but that doesnt seem to do it.

Ok, I was able to figure this out picking apart some code I pillaged from a friend.
Everything was ok, the problem was the updating
When I was saving the data, i was calling just:
Me.TblProptertiesTableAdapter.Update(Me.TblPropertiesBindingSource.DataSource)
The correct code, without changing anything else is:
Me.Validate()
Me.TblPropertiesBindingSource.EndEdit()
Me.TblPropertiesTableAdapter.Update(Me.RentalPropertiesDataSet.tblProperties)
Me.RentalPropertiesDataSet.AcceptChanges()
Where RentalPropertiesDataSet is the database where TblProperties comes from. Inorder for this to work, make sure TblPropertiesBindingSource.DataSource is RentalPropertiesDataSet.Properties This was autosetup for me by VS08 when it created the BindingSource.
Basically, I needed to tell teh BindingSource to stop allowing the fields to be edited. Then we save the changes to the database, and lastly we tell the DataBase to accept the changes.

Related

Open a form to a record selected in a subform

I want to open a form to the record selected in the subform of a different form. I've tried following what I’ve seen in other posts about this, but I still can't get it to work. I think I'm just missing some very basic detail but this is my first Access database and I can't figure out what it is. Thanks in advance for your assistance.
Details:
F_Detail - (This is a Single Form containing details on a project.)
F_List - (This is a Single Form containing a subform and a button.)
subF_List - (This is the subform contained in F_List. This subform is in Datasheet view)
Project_ID - (This is the primary key contained in subF_List and in F_Detail. It is the common criteria between the two. It is Short Text type.)
subF_List displays row after row of projects. F_Detail displays details about a single project at a time. From F_List I want to select a row in subF_List and then click the button to open F_Detail, and F_Detail will be displaying details of the project whose row was selected in subF_List when I pressed the button.
What I Have for the Button:
On Click > Event Procedure
Private Sub ProjectDetailButton_Click()
DoCmd.OpenForm "F_Detail",,,"Project_ID = " & Me.Project_ID
End Sub
Upon clicking the button, I get an error saying, "Compile error: Method or data member not found" and it highlights the .Project_ID at the end of my code.
I don't know what I'm doing wrong and would appreciate any help you can lend. Please let me know if I've left out any needed detail.
Use apostrophe delimiters for text field parameters. Use # for date/time, nothing for number.
"Project_ID = '" & Me.Project_ID & "'"
Me is alias for form or report the code is behind. To reference a field in its RecordSource:
Me!Project_ID
Code on main form referencing field on subform must reference through subform container control. I always name container different from object it holds, such as ctrProjects:
Me.ctrProjects!Project_ID
I name controls different from fields they are bound to, such as tbxProject:
Me.ctrProjects.Form.tbxProject

MSAccess VBA: Pass values from a subform to a seperate form

I have a form frmDetail that contains several locked fields I want populated only when another form has been filled out, in the name of having some kind of standardization in my data. This other form frmSignOut is used to enter in a date and location that will populate the fields on frmDetail. frmSignOut also contains a subform subULookup that looks up users from a different table using an identifier number. The resulting last name, first name and phone # should also be passed to frmDetail. I also hope to combine first and last name somehow into a Last,First format.
My approach so far has been to open frmSignOut modally with acDialog and I inserted Visible=False into the On_Click event on frmSignOut. Then I try to reference my subform fields and set them to the desired fields on frmDetail. I finish by refreshing and then closing the dialog form.
Private Sub CmdSignOut_Click()
DoCmd.OpenForm("frmSignOut"),,,,,acDialog
If CurrentProject.AllForms("frmSignOut").isLoaded=True Then
Set Forms!frmSignOut!SubULookup.PhoneNbrTxt=Me.ContactNbrTxt
DoCmd.Close (acForm), ("frmSignOut")
Me.Refresh
End If
End Sub
I have only been able to get this far, trying to pull the first field PhoneNbrTxt. I can get frmSignOut to open, I put in data and when I click my 'close' command button I get run-time error 438: Object doesn't support this property or method.
The line highlighted is where I try to reference my subform field. I also have a 'Cancel' button added to frmSignOut that just closes the form, I have no errors there.
Again I'm completely new to Access without much prior experience in anything related, I'd appreciate any knowledge you guys can throw at me.
EDIT: I've been able to successfully pull the value to Me.ContactNbrTxt by adjusting my code to the below.
Me.ContactNbrTxt = Forms!FrmSignOut!SubULookup.Form!PhoneNbrTxt
It looks like the missing part was the Form! right before the control name, along with formatting this correctly and dropping Set.
Im still trying to work out how to combine first and last name before also pulling those to frmDetail, if anyone can help there.

How to allow user to select individual UserControls?

I'm working on a windows form app containing a TabControl. In one of the TabPages I have a GroupBox that contains a FlowLayoutPanel. I also have a SQL database table containing user notes/comments. Upon form load, I use a SqlDataReader to populate a user control for each note (creation date, note text, username, etc.). The FlowLayoutPanel then gets filled by UserControls. However, I would like for the user to be able to select individual notes/UserControls for editing/deleting. I was initially using a DataGridView instead of UserControls, but notes vary in length and the DataGridView didn't look very organized. My UserControl contains a self-expanding RichTextBox. I thought about adding CheckBoxes next to each UserControl, but I'm not sure how to track which box belongs to which UserControl. Is there a smarter way to accomplish this?
This is a url for a screenshot of the UserControl: https://imgur.com/a/ZN7MM
(I don't have enough reputation to post images.)
And here is the code I got from another post on the self-expanding richtextbox:
Private Sub RichTextBox1_ContentsResized(sender As Object, e As ContentsResizedEventArgs) Handles rtbNote.ContentsResized
rtbNote.Height = e.NewRectangle.Height + 10
End Sub

How to set default values for data bound controls for addition in VB.NET

I have a vb.net 2010 form with 22 data bound controls from two tables held in a dataset which is navigated by a bindingnavigator. This successfully adds deletes and updates. However what I need is when adding a new record I need some of the fields to be pre filled out. More specifically I have points balance fields etc which could be any value but will normally be 0 on a new customer so I want to initialise them to 0 when adding new records.
I located an AddingNew event on my datasource but this is called before the new item is added and thus all my initialisation is lost.
any help on this would be appreciated.
kind regards
Feldoh
Since you are using DataTables, you can manually set the DefaultValue property of the DataColumn:
Dim dt As New DataTable
Dim dc As New DataColumn("test", GetType(String))
dc.DefaultValue = "hello"
dt.Columns.Add(dc)
dt.Rows.Add()
Debug.WriteLine(dt.Rows(0)("test").ToString)
Result: hello
Answer including multiple linked tables solution:
Like LarsTech said using
dataset.table.Columns.Item("someField").DefaultValue = someValue
works nicely if you have a standard default but it also works for generated defaults, if you reset this default on saving to the next value you want if a new addition is made. However if you are using a dataset as your data source where a child table record cannot feasibly be generated (like in my case where an account id will be generated only on saving using a database trigger to link all different kinds of accounts) you can still set defaults for the other fields, the ones from the sibling (or non-existent parent) table but
dataset.siblingTable.Columns.Item("someField").DefaultValue = someValue
WILL NOT WORK as the binding navigator only generates the first sibling and the parent is not generated until the trigger. However on the BindingSource.PositionChanged event of the binding source that IS generated by clicking add you can freely put defaults into the actual controls on the screen and they will not be overwritten by nulls, clearly you need to restrict this so it only happens if the user pressed add by adding a variable to the Clicked event of the add button to tell you when add has been clicked and resetting this variable on save or roll-back. It is also possible to modify the bindings themselves which have an if null or empty default value.
Hope this helps someone else :)
Use the MouseUp event on the 'Add Row' button in the BindingNavigator instead of the "Click" event. This is becouse the new ROW does not exist in the datagridview until AFTER the click event is completed.
Private Sub BindingNavigatorAddNewItem_MouseUp(sender As Object, e As MouseEventArgs) Handles BindingNavigatorAddNewItem.MouseUp
'works with add row from the binding navigator
myDataGridView.Item(3, myDataGridView.CurrentRow.Index).Value = txtDefaultDescrip.Text.Trim
End Sub
to do this same thing when adding data directly in you DataGridView do this.
Private Sub myDataGridView_DefaultValuesNeeded(sender As Object, e As DataGridViewRowEventArgs) Handles myDataGridView.DefaultValuesNeeded
'works with add row inside a datagridview
e.Row.Cells(3).Value = txtDefaultDescrip.Text.Trim
End Sub
In this example I have a editable default value shown on my from. If you have a non-changing default value (e.g., is always 1 for column 3) then you should do that when setting up your datasource.

Updating a control on another form with the results of a dialog box

I made a windows form which contains a listbox (named VenueList). The listbox is pulling it's values from a list provided by a binding source VenuesBindingSource which is pulling in a ID for the value and a name for the text.
There is a button which is causing a DialogBox to appear which is asking for values to store in the database for a NEW venue. Once the values are filled and insert the database, what's supposed to happen is that the dialog box closes and goes back to the original form which invoked it.
However, instead of updating the list. The list stays the same. But if you close the form and reopen it, you see that a new value was added.
TournamentSettings.VenuesTableAdapter.InsertVenueQuery(Trim(VenueNameTxt.Text), Trim(VenueAddress1Txt.Text), Trim(VenueAddress2Txt.Text), Trim(VenueCityTxt.Text), Trim(VenueProvinceTxt.Text), Trim(VenueZipTxt.Text), Trim(CountryBox.SelectedValue), Trim(VenuePhoneNo.Text), VenueType.SelectedText, VenueWebAddress)
TournamentSettings.VenuesTableAdapter.Fill(TournamentSettings.VenueNameList.Venues)
In the above code, InsertVenueQuery is the name of a query from the designer which is invoked to add the values onto the tableadapter VenuesTableAdapter which is used to fill the combo box on load. I also sent the Fill command to refill the table with the new value.
So the question is, should I go about doing this another way, rather than feeding the Table adapter and sending a fill command on to the datatable? Or is there something that I'm not doing here which I should to force that value into the list. I'm tempted to redo everything outside of the designer but that's a lot of code since I have to essentially run two commands (one to insert the data, and another to get the ##IDENTITY value since this is run on an access database.)
Okay. This one I had to think about for a moment.
Instead of me creating a block of done on the load event, I instead created a sub function called "FillVenueList".
I used the following block of code:
Public Sub FillVenueList()
' Adding values from database to a datatable.
' From there will add to the list box.
Dim VenueConnection As New OleDb.OleDbConnection(DBconnection)
VenueConnection.Open()
Dim VenueConnectionQuery As New OleDb.OleDbCommand("SELECT VenueID, VenueName FROM Venues", VenueConnection)
Dim VenueDataAdapter As New OleDb.OleDbDataAdapter(VenueConnectionQuery)
Dim VenueDataSet As New DataSet
VenueDataAdapter.Fill(VenueDataSet, "Venues")
TrnVenueLst.DataSource = VenueDataSet.Tables("Venues")
TrnVenueLst.DisplayMember = "VenueName"
TrnVenueLst.ValueMember = "VenueID"
VenueConnection.Close()
End Sub
From there I called THIS sub on both the form AND the Add Venue window and I can safely see that this works. SO THAT is how you get a new value onto the form, don't use it as a part of the Load Event but rather call it from the load event block, then call it when you want to add to the list.