VB.Net ComboBox (as Dropdown) not translating text to DisplayMember with Databinding - vb.net

I inherited a fairly large project at work that is undocumented and written in VB (originally started pre .NET, ended around .NET 2). I'm in the process of updating / refreshing a lot of the code, but have run into an annoying issue that I haven't found the solution for yet. This system utilizes a UI, a Web Service, and a SQL DB.
Problem: I have a Databound Combobox (originally set to DropDownList - I'm changing it to DropDown, which is what started this mess - going back isn't an option) that is tied to a DataSet that comes from a Web Service. When a user types in the item they want manually, the data from the text field doesn't seem to associate itself with the DisplayMember, which forces the WS/SQL query to fail (it is sent a blank value when it's expecting a ValueMember). If the user types in a partial selection and then chooses the value they want from the DisplayMember list using the arrow keys or tab, the query goes off without a problem.
My Question: How do I get the text field to translate to the DisplayMember which will then properly tie itself to the ValueMember which will then allow the query to execute correctly? Sorry for making this sound complicated or convoluted; I'm sure the answer is easy and I'm just glazing over it.
The relevant bit of code is:
With cmbDID
If dtsLU.Tables.Contains(reqTable) = True Then
.DataSource = dtsLU.Tables(reqTable)
.DisplayMember = "zip"
.ValueMember = "gridID"
End If
End With
cmbDID.DataBindings.Clear()
cmbDID.DataBindings.Add("SelectedValue", dtsData, strDT & ".gridID")
I've tried changing "SelectedValue" to "Text", which almost works - but it directly translates to gridID and skips zip which ends up with an incorrect Web Service response since the zip and gridID field values are not synced (zip (DisplayMember) may be 5123 while gridID (ValueMember) may be 6047). I've tried changing "SelectedValue" to "SelectedIndex", and that got me no where.
Any help is greatly appreciated.
EDIT
To add some clarification to the process, the below pseudo code / description is roughly what happens. I could post the whole module, but I feel that would just muddy the whole question even more.
Private Sub A
FormAlpha is created with 1 ComboBox in the form of a DropDown
This DropDown is populated with a DataSet
DataBinding with a blank DataSet is added to the control to keep track of the users input
End Sub
lblSubmit_Click event is triggered on FormAlpha by the user after they have populated the DropDown with their data. lblSubmit_Click calls Private Sub Submit
Private Sub Submit
BindingContext(DropDown DataSet, tableName).EndCurrentEdit() is called
DataSet.HasChanges() is processed
If changes are present, changes are processed
HERE lies the problem
If the user has manually typed in the DropDown field, but not hit an arrow key or tab, then the DataSet registers a change, but returns a null value in all fields - it knows something was entered, but that data apparently didn't pass through the DataSet for the ComboBox (ListItems or SelectedIndex didn't change / fire I'm guessing). If the user selects the item with the arrow keys, the DataSet has the proper input (I'm assuming the Data was validated by the control at this point).
If the processed data is good, a value is entered into the database
If the processed data is bad (empty), an error is returned
End Sub
If the above can't be solved with what I've provided, but someone still knows a better way to handle this type of situation, I'm all ears. Rewriting the module isn't ideal, but fixing this problem is a necessity.

Alright, while this fix may not be ideal, it is a fix none the less.
The bare bones problem was that the text value of the DropDown wasn't causing the data to actually affect the SelectedIndex / SelectedValue of the control unless you interacted with it using the arrow keys or a mouse click. So, while the DropDown would read "1234", in reality the control saw "".
The fix I have in place for this is simply calling comboBox.text = comboBox.text whenever the user hits the submit button.

Related

Why did I have to manually set the .value from the .text on losing focus in an unbound textbox

I have an unbound textbox to accept the delete older than: number of days. It is in the report header. I set it to 30 days but I want the user to be able to change it. I was banging my head trying to figure out why entering 40 was not being accepted and it reverted back to 30 every time. I finally decided on using the lost_focus event to set .value to .text. That worked.
Further research showed that when the textbox get's focus text and value are both the same, 30 in my case. Changing the number in the text box to 40 shows the values of text at 40 and value at 30. Unless I specifically set Value to the value of text Access changes text to the value of value. This is different behavior than other places in Access such as forms.
Can anyone tell me why this might be? I can't find any setting that might do this. Is it because it's in a report header? what is the difference between this and every other text box I've ever used?
From a "best practices" viewpoint, Access Reports are not intended to be used interactively despite the ability to manipulate some unbound controls. Although workarounds can be implemented that function sufficiently well, such solutions are often incomplete and buggy and function differently depending on the active view: Report View vs. Print Preview. Appropriate design patterns include using Access Forms for specifying report options which then open the Report in a static configuration.
This may not satisfy the question "Why?" if seeking a deeper answer as to why Microsoft implemented inconsistent binding behavior in Access, or why they allowed interactive controls in reports at all if they don't behave the same way as in forms. But Access has plenty of other quirky behaviors that have no known/published explanation.
Regarding the priority of the Value property updating the Text property (and not vice versa): Value is the key field because it contains the actual data for the control (bound or unbound). Although it is natural to have a single control for both display and input (uh, that's how almost all controls work), the processes of displaying data and parsing user input are two distinct functions. The visual representation returned by the Text property can be manipulated using the various formatting properties, and technically could display an incomplete representation of the underlying Value data. If there are any conflicts between the stored Value property and the Text property, it is natural that the existing Value property has precedent.
My guess is that the automatic binding behavior was "relaxed" for reports to allow more flexible custom reporting output. First consider an Access Form in Datasheet view: An unbound Form control shows the same value for all records. Even if the control is edited while on a particular row, the updated value is displayed for all rows. The same control object is essentially repainted for each row and there is no concept of individual instances of the control that can hold different values. Bound controls have built-in code that repaint the control with data from the particular row, but there are still not multiple instances each "holding" the individual values. The visual output differs from an intuitive object-oriented paradigm where our minds what to assign each visual row its own in-memory instance of the controls--it just doesn't work like that in Access.
Unlike the Form behavior just described, the Report's Print Preview (and actual printed output) allows unbound controls to display different data per row using the Detail_Format() event. Within the Detail_Format() event, one can set the Value property of a control at which time the Text property is automatically updated according to various formatting properties. This update Text is then output for the current row. Perhaps (just guessing) that this behavior would not function properly if the Text property updated the value property. I suspect it would cause recursive events during report generation. Because reports are not meant to be interactive, relevant text-input parsing code was "disconnected" so that it doesn't behave like on a form.
All that explanation doesn't make Access any less frustrating nor remove its limitations, but at least learn to adapt and design things in the "Access-esque" way rather than fighting it.
your best bet is to design a form with the unbound combo boxes and have your data displayed in a subreport. I like to design my reports so that when values are updated the query for the recordsource of the report is generated doing this requires 2 queries to exist, one with all data possible and a filtered one as subreport recordsource. This will control the data for printing and also allow users to close or navigate away from the report and return to the data later.
Private Sub ComboBox1_AfterUpdate()
Dim Query1 as Object
Dim Temp_Name as Variant
Temp_Name = SubReport.SourceObject
SubReport.SourceObject = Empty
Set Query1 = Me.Form.Application.DBEngine.Workspaces(0).Databases(0).QueryDefs ("SubReport_Query")
Query1.SQL = "Select * Unfiltered_Query WHERE Field1 <= " ComboBox1 & ";"
SubReport.SourceObject = Temp_Name
End Sub

My.Settings "Destination array was not long enough. Check destIndex and length, and the array's lower bounds."

I have two forms with combo boxes. The combo box values are stored in My.Settings.testDevices. (System.Collections.Specialized.String.Collection) with a scope of User.
The second form adds the ability to add items to testDevices, and then upon exit it updates My.Settings.testDevices.
Now, only if I make a change to the settings (adding items only), when I exit back to the main form (which remains loaded throughout the process), my application crashes with the following message:
"Additional information: Destination array was not long enough. Check destIndex and length, and the array's lower bounds."
As I understand it, this might be a concurrency issue, however I'm not sure.
My code:
In my main form Load event: (to load from My.Settings)
testDevicesComboBoxMain.Items.Clear()
My.Settings.testDevices.CopyTo(mainFormTestDevices, 0)
testDevicesComboBoxMain.Items.AddRange(mainFormTestDevices)
Where "testDevicesComboBoxMain" is the combo box on the main form.
On the secondary form Close Event: (to save to My.Settings)
Dim items(testDevicesComboBox.Items.Count - 1) As String
testDevicesComboBox.Items.CopyTo(items, 0)
My.Settings.testDevices.Clear()
My.Settings.testDevices.AddRange(items)
My.Settings.Save()
I have found similar questions on here, but none with answers that I understand :P
As I am a beginner with vb.net, could any answers be provided in an easy to understand form please!
Thanks.
I forgot to add:
Public items(My.Settings.testDevices.Count - 1) As String
Public mainFormTestDevices(My.Settings.testDevices.Count - 1) As String
I tried setting separate declarations just in case there was some kind of conflict. These obviously do the same thing, just with different names.
I fixed it by adding a For loop to read from My.Settings.
For Each i As String In My.Settings.testDevices
testDevicesComboBoxMain.Items.Add(i)
Next
This seems to have cured the problem, and may perhaps be a more "modern" way of doing it?

SqlDataSource ControlParameter not working

I have a dropdown (selProject) populated by a SQL table. The value is the id field, the name is the name field.
I have a gridview control fed by a sqldatasource.
What I want to do is to conditional where clause based on the selProject dropdown. I have spent 3 hours searching and trying to figure this out. I fear I am going to snap and kill a co-woker.
When I choose a specific value in the dropdown, the selectedValue of the control is "40". I verified this through debugging. This is correct and expected.
I have a controlParameter that looks like:
<asp:ControlParameter ControlID="selProject" PropertyName="SelectedValue" Name="ProjectIDPass" Type="Int32" />
The SelectCommand includes: (Batches.ProjectID = #ProjectIDPass) as part of the Where clause.
I get no rows, no errors, no problems. The issue I suspect is that the SelectedValue of the dropdown is a string and the Batches.ProjectID is an integer.
When I hard code 40 into the where clause in place of #ProjectIDPass, it works great. When I go back to the ControlParameter is bombs out. I have tried all manner of conversion techniques.
Is there any way to see the SqlDataSouce SelectCommand that was executed with actual values in place of the parameters.
The issue I suspect is that the SelectedValue of the dropdown is a string and the Batches.ProjectID is an integer.
Doubtful - the Type property handles the conversion, and your RDBMS would as well (though it'd probably convert the int column to string, screwing your indexes).
Is there any way to see the SqlDataSouce SelectCommand that was executed with actual values in place of the parameters.
A RDBMS profiler like Sql Profiler would be the best way. But you can also hook the SqlDataSource.Selecting and SqlDataSource.Selected events and examine e.Command and e.Arguments.
So I solved my issue, and it was a complete lack of understanding how GridViews are handled.
I wanted to load data based on values from 2 Drop Downs without doing a post back. This way, a user can go from page to page and not have to keep setting dropdowns. That isn't possible till the page is loaded, as the dropdowns are not set until the page load is nearly complete. Gridviews are populated on Page Init. I could use the cookies I was setting to set the data in SQL query, but if the user changes a drop down, the cookies are not reset with the new data until the page loaded, so I would be loading the wrong data.
I found a solution, which is to allow the page to load, then use the values of the boxes which are set properly at that point, and use them to query a dataset and asign it to the GridView. The trick to get it to actually display the data since the page is fully loaded at this point, is an update panel.
See this article for full description: http://www.aspsnippets.com/Articles/Bind-Load-GridView-after-Page-load-is-completed-using-AJAX-UpdatePanel-in-ASPNet.aspx

Microsoft Access 2013 Form Objects

I have a database that was create in Access 2010. We recently updated our systems to Access 2013. In Access 2010 I have no errors accessing a form object with
Form_frmName.txtFieldName.Value
However, when using Access 2013 I get a runtime 2424 error stating that "The expression you entered has a field, control, or property name that Microsoft Access can't find. I am accessing from a module.
The module sets these fields visible using
With Form_frmName
.txtFieldName.Visible = True
End With
before attempting to access them.
Has there been any changes in the way form objects are accessed between 2010 and 2013? Is this an issue others have faced?
In Response to #WayneGDunn's questions below
QUOTE:
I need to know exactly what and how you are using this.
1. You have a bound textbox named 'txtFieldName' on a form. As #brad asked, is there a subform, and if so, is this field on the subform?
2. You said the code is in a module, but is the code in the form where the field is defined?
3. Please explain where/what form 'frmQAtab' is (you said your form name was 'frmName', so what is the other, how related?)
4. Is the code in an event? Can you share the entire subroutine?
5. Have you tried creating a dummy query and using the builder to reference the field?
RESPONSE:
1. I have a form (frmMain) with multiple tabbed pages. frmName is one of those tabs, containing the bound field txtFieldName.
2. The module is run from the form the field is in.
3. My apologies frmQAtab is frmName, I just neglected to make that generic in my copy-paste.
4. The event is a button click. The button click runs a sub from a module. That sub makes visible the fields, runs a query based on user input (two date fields), populates the bound fields with the returned record set, then attempts to access them for processing (another query is run to process a complete other set of fields). To post the entire subroutine would be a bit more than I would ask you to chew on. This is legacy code I'm trying to fix, and it's rather large.
5. I have not tried a dummy query. Access is not my field (I'm mainly a C#, scripting, guy.) Is there some suggestions in this area you could give?
One of the following references to your fields should work. I created a form (named 'frmMain'), then created a Tab Control with two tabs. On the first tab, I inserted another form (named 'frm3197'). I also created a text box on the tab control named 'txtFieldName' AND in form 'frm3197'. From a button click on 'frmMain', the following will reference each of those fields.
Private Sub cmdButton1_Click()
Forms![frmMain]![txtFieldName] = Now()
Forms![frmMain]![frm3197].Form![txtFieldName] = Now()
End Sub

data from Gridview to textbox

i have a form with datagridview in vb.net that show my data in columns. what i'm trying to accomplish is that after choosing a row and pressing Edit button a new form will open and split the row for the right text boxes to update the data. the datagridview row shows different types of data: name,email,date,etc... any idea? Thanks in advance!
In the EditButton click-handler, you may access the selected row in your datagridview with the MyDataGridView.CurrentRow property.
This object - a DataGridViewRow - has Cells, which you can access individually by index and then get to their values:
...CurrentRow.Cells(n).Value
This then, in turn, you may use to fill the items in your edit form.
After completing your edit form, retrieve the (updated) values and put them back into the CurrentRow.Cells(n).Value
If your datagridview is databound, then you can also work directly with the datastore, through
...CurrentRow.DataBoundItem
The type of this object depends of course on your configuration; it may, for instance, be a DataRow.
This should be enough to get you going.
Final note on your added remark "thanks ...": you're apparently new at this site. I'm not sure why you got "downvotes". It may be because your question is rather elementary ("homework"), or people found your problem description not clear/detailed enough. Please, understand that answers (if any) are provided "unpaid for", and require "voluntary" effort from the contributors. Understandably they prefer that YOU do most of the work/study/trying, before asking someone else "to do your work for you". No offense intended.