vb2010 - TextBox1.Text from MS Access record - visual-studio-2010

I am new to vb2010 and have been successful with google searches for all my previous problems but this one i cannot make any traction on so I am looking for a little help on the correct syntax.
Public Class Form2
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'IRuleDataSet.Stnds' table. You can move, or remove it, as needed.
Me.StndsTableAdapter.Fill(Me.IRuleDataSet.Stnds)
'Populates listbox1 with data from iRuleDataSet table
ListBox1.DataSource = IRuleDataSet.Stnds
ListBox1.DisplayMember = "Standards"
ListBox1.SelectedIndex = 0
End Sub
Private Sub StndsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.StndsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.IRuleDataSet)
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Label2.Text = ListBox1.Text & " IRule"
'~~>This is where I am stuck
'~~> TextBox1.Text = IRuleDataSets.Stnds.IRule.ListBox1.SelectedIndex bah i can't get this ):
End Sub
End Class
in form 2, I have loaded an access database into a DataSet labeld IRuleDataSet.Stnds
Table = Stnds
Field = IRule
Record Position = ListBox1.SelectedIndex
what would be the correct syntax or naming convention/logic to have the corresponding text for the record position in Field: "IRule" that the user selects in ListBox1 to display in TextBox1?
This isn't for any schooling subject or anything like that. This is merely a learning exercise for myself to put together a GUI for calculations that are currently done in an overly complicated xls file at my work, so any help would be appreciated. I don't know if it is becoming too late for me or not but I just cannot seem to find the correct way to approach this seemingly simple task.
Thank you

AHA!
sure enough as soon as i post a question i find the correct solution
TextBox1.Text = IRuleDataSet.Stnds(ListBox1.SelectedIndex)(2).ToString
what this does, it sets TextBox1 text to look in to the imported access file (as IRuleDataSet.Stnds) then looks at the 'row' (ListBox1.SelectedIndex), and then the column number (2). i know this is 2 because when i put in my dummy data in the database, the field of interest was the second column.
i hope this helps future googlers (:

Related

How do I add a save feature to a datagridview?

Hi i am fairly new to visual studio and I am having some trouble adding a save feature to my program. Basically what my program does is set event reminder for the user (it's like a daily planner but with no notifications). I have got the "add event', "delete", and "update buttons to work on the program and now all I have left is the "save" and "load" key. What I am trying to do is find a way to save the DataGridView so it can be opened back up in the program at a later date using the "load" key. If it would be easier to just remove the "load" and save the info right into the event reminder application, I could go that route but I don't have the first idea how to do that. This is what I have right now for the code in the main form:
Public Class MainForm1
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If DataGridView1.Columns(e.ColumnIndex).Name = "Delete" AndAlso Me.DataGridView1.Rows(e.RowIndex).IsNewRow = False Then
Me.DataGridView1.EndEdit()
Me.DataGridView1.Rows.RemoveAt(e.RowIndex)
End If
If DataGridView1.Columns(e.ColumnIndex).Name = "Column4" AndAlso Me.DataGridView1.Rows(e.RowIndex).IsNewRow = False Then
Dim Update As UpdateWindow
Update = UpdateWindow
Update.Show()
End If
End Sub
Private Sub dltBtn_Click(sender As Object, e As EventArgs)
Dim dltBtn As dltWindow
dltBtn = dltWindow
dltBtn.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Button1 As addBtn
Button1 = addBtn
Button1.Show()
End Sub
Private Sub UptBtn_Click(sender As Object, e As EventArgs)
Dim UptBtn As UpdateWindow
UptBtn = UpdateWindow
UptBtn.Show()
End Sub
Dim thisFilename As String = Application.StartupPath & "\Event reminder.dat"
Private Sub saveBtn_Click(sender As Object, e As EventArgs) Handles saveBtn.Click
Me.Validate()
Me.SaveGridData(DataGridView1, thisFilename)
End Sub
Private Sub BtnLoad_Click(sender As Object, e As EventArgs) Handles BtnLoad.Click
Me.LoadGridData(DataGridView1, thisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal thisFilename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(thisFilename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, " "))
Next
End Sub
End Class
I have gone on the other forums and asked about how to do this and they all said the bind the datagridview to a data table. If that is the route I have to go, how do I go about it? If anyone has some examples or code I could try out I would be much appreciative.
The problem I can see in the posted code is between the LoadGridData and the SaveGridData methods. When the LoadGridData method runs, it reads a file where each line is “Split” on spaces “ “. This is fine and if the file is properly “space” delimited it works as expected. So let us assume everything works and the data displays in the grid properly.
Then the user presses the saveBtn which calls the SaveGridData method. The code appears to “select” all the cells in the DataGridView to the clipboard, then proceeds to write the clipboard text to the SAME file name used when loading the grid. This also appears to work as expected.
The problem with this is that when the code copies all the cells of the DataGridView to the clipboard then, writes this copied clipboard text; it will use a “Tab” delimiter. The file Event reminder.dat which was read in using a “space” delimiter will be overwritten with a “tab” delimiter and not a “space” delimiter. Therefore, then next time the load method is run… it will fail.
If the load and save button are going to read the same file, then they MUST both agree on what character is used as a delimiter. You can use whatever character you want as a delimiter. You can use a “space” as the posted code does, however this limits each type to a string with no spaces. If one of the fields is a home address, chances are good, there will be a space in the string. Using a “space” as a delimiter is not necessarily the best of choices.
A simple solution is available with the current code. Currently if the file Events reminder.dat is space delimited and reads in properly to the data grid view, then it should be easy to replace the space delimiter with something else. In this case, since the SaveGridData method is delimiting the fields with a “tab” then we simply need to change the load method to “split” on “Tabs” and not “spaces” when reading back the file.
Step 1 – make a copy of Events reminder.dat
Step 2 – Run the program, press the load button and make sure all the data is properly loaded into the grid.
Step 3 – If the data is displayed properly in the grid, press the save button. (Updates file with tab delimiters)
Step 4 – Exit the program and make the change below in the LoadGridData method.
ThisGrid.Rows.Add(Split(THisLine, vbTab))
Step 5 – Run the program. Now both the load and write methods agree on what character (Tab) is used as a delimiter.
Lastly, to comment on using a DataTable the answer would be yes. DatagridViews and DataTables play nicely together. Hope this helps.
You may want to take a “Tour” of Stackoverflow to see how it works.

Conversion.VAL method - Global Hook

Our application is very large and we have been using VAL method a lot to ensure that data input in the textboxes is converted properly into related numbers. However, now we ran into few issues. For example, if someone writes 25,500, the VAL function will return 25 instead of 25500. Seems like it is expected behavior as VAL method stops proceeding once it find nonconvertible character like comma.
I would like to know if there is a way to have a global hook for this method I can create in my application, so that whenever I call a VAL method from my application, it should call my defined method, instead of calling from the Microsoft.Visualbasic namespace.
thank you
With a textbox a button and a label on the form this seems to do the trick.
Make a convert sub and call it.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim result, middle As String
Dim newresult As Double
If TextBox1.Text Is Nothing Then
MsgBox("Empty TextBox!")
End If
result = (TextBox1.Text)
middle = result.Replace(",", String.Empty)
newresult = Val(middle)
Label1.Text = newresult.ToString
TextBox1.Text = Nothing
End Sub
Hopefully this helps. newresult is preserved as a double for further use, and the value is displayed only for clarity in this example

Handling GotFocus / LostFocus events on all TextBoxes in a Form VB6

I would like to create a handler which listens GetFocus / LostFocus events for all TextBoxes in a Form using VB6 how can I achieve that?
What i tried so far:
Option Explicit
Dim Cnt As Control
Private WithEvents Txt As VB.TextBox
Private Sub Form_Load()
For Each Cnt In Me.Controls
If TypeOf Cnt Is TextBox Then
Set Txt = Cnt
End If
Next Cnt
End Sub
Private Sub Txt_GotFocus()
Txt.BackColor = &H80000018
End Sub
Private Sub Txt_LostFocus()
Txt.BackColor = &H80000005
End Sub
but this only works for one TextBox in the Form
this only works for one TextBox in the Form because Txt can only refer to one textbox at a time.
One way to have a common handler is to create your Texboxes as a control array. Give them all the same name (ie txtBox). VB will automatically make an array of them. You can control their order in the array using the Index property. Now, your LostFocus will look like this:
Private Sub txtBox_LostFocus(Index As Integer)
txtBox(Index).Backcolor = &H80000005
End Sub
If you need to change what you do based on WHICH textbox it is, use the Index to tell which one it is. NOTE: Control arrays are quite handy, but they disappear in VB.NET. There are some equivalent methods but I would not get too attached to the exact way they work.
For more complex ops, the several events can call a common procedure passing the control as an argument.

Google Drive SDK - Populate .NET TreeView with Google Drive directory structure

I'm building a VB.NET Google Drive file explorer application for reasons that you probably do not care about. I'm using the google drive v2 sdk, and I'm trying to populate a tree view control with a user's entire Google Drive directory structure (not files, just folders.) My code is working fine, however, as I feared, it is taking several minutes for users that have a whole lot of nested folders. I am using a background worker thread to populate the treeview using a delegate function. Can anyone suggest a more efficient way of doing this?
NewPopulate() is called from my code to create the background worker threads. Start here:
Private Sub NewPopulate()
TreeView1.Nodes.Add(ActiveUser.Email, ActiveUser.Email)
bwPopulateTree = New BackgroundWorker
AddHandler bwPopulateTree.DoWork, AddressOf PopulateTreeStart
AddHandler bwPopulateTree.RunWorkerCompleted, AddressOf PopulateTreeFinished
bwPopulateTree.RunWorkerAsync()
cmbActiveUsers.Enabled = False
End Sub
Private Sub PopulateTreeStart()
Dim children As ChildList = FileManager.GetFoldersInFolder(ActiveUser.DriveService, "root")
PopulateTreeLoop(ActiveUser.Email, children)
End Sub
Private Sub PopulateTreeFinished()
lblToolStripStatus.Text = "Directory listing completed."
SaveTree()
cmbActiveUsers.Enabled = True
End Sub
Private Sub PopulateTreeLoop(nodeKey As String, ByVal childList As ChildList)
If Not childList Is Nothing Then
Dim user As GoogleUser = ActiveUser
For Each child As ChildReference In childList.Items
Dim successful As Boolean = False
If TreeView1.InvokeRequired Then
successful = TreeView1.Invoke(New m_FindAddNode(AddressOf FindAddNode), {nodeKey, child})
Else
successful = FindAddNode(nodeKey, child)
End If
Dim children As ChildList = FileManager.GetFoldersInFolder(user.DriveService, child.Id)
If Not children Is Nothing Then
PopulateTreeLoop(child.Id, children)
End If
Next
End If
End Sub
Private Function FindAddNode(nodeKey As String, child As ChildReference) As Boolean
'Returns true if successful
Try
Dim service As DriveService = ActiveUser.DriveService
Dim file As Drive.v2.Data.File = service.Files.Get(child.Id).Fetch()
Dim node() As TreeNode = TreeView1.Nodes.Find(nodeKey, True)
Dim strTitle As String
If file.FileExtension Is Nothing Then
strTitle = file.Title
Else
strTitle = If(file.Title.EndsWith(file.FileExtension), file.Title, file.Title + file.FileExtension)
End If
node(0).Nodes.Add(file.Id, strTitle)
Return True
Catch ex As Exception
Return False
End Try
End Function
And here is my FileManager class function:
Public Shared Function GetFoldersInFolder(service As DriveService, ByVal folderId As String) As ChildList
Dim request As Google.Apis.Drive.v2.ChildrenResource.ListRequest = service.Children.List(folderId)
request.Q = "mimeType='application/vnd.google-apps.folder'"
Return request.Fetch()
End Function
Sorry I had to include so much code, but I tried to include only that which is necessary. I also already have code which allows me to cache the directory structure, but decided it will be hard to implement, since I will have to be checking to make sure things haven't changed... I really just need a faster way of retrieving the directory structure. I know another way of doing this is to have the treeview only populate the subfolders once a user clicks on the parent folder, but I would like to avoid the short pause which comes from waiting for the server to respond to each request, every time the user clicks on a new folder.
I also have a function which retrieves ALL folders:
Public Shared Function GetAllFolders(service As DriveService) As FileList
Dim request As Google.Apis.Drive.v2.FilesResource.ListRequest = service.Files.List
Dim request2 As Google.Apis.Drive.v2.FilesResource.ListRequest = service.Files.List
request.Q = "mimeType='application/vnd.google-apps.folder'"
Return request.Fetch()
End Function
But I can't come up with any efficient way to parse that list to come up with a directory structure... Any ideas? I really appreciate the help. I've been working on this for days...
Your method is reasonable. Sorry it is taking a long time with large Google Drives. I certainly think that you are on the right idea in only populating the child nodes when the user attempts to expand the parent. The pause there is expected, but you can mitigate it somewhat by displaying some feedback to the user, e.g. Loading....
In this age of cloud computing, users expect some delay when loading data from a remote service. This will improve in the future as network speeds improve.

Visual Basic 2010 Listbox Error

what is the meaning of this error? sorry it's my first time to use Visual basic 2010, I'm not familiar with this kind of error, I use this for selecting all the files in the listbox and tried to move or copy to another listbox in other form.
Error 1 'ToArray' is not a member of
'System.Windows.Forms.ListBox.ObjectCollection'.
This is the code I use.
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
If RadioButton1.Checked Then
Dim itemsToMove = ListBox1.Items.ToArray()
For Each item In itemsToMove
Form2.lstP.Items.Add(item)
ListBox1.Items.Remove(item)
Next
Form2.Show()
End If
End Sub
Can someone help me with this?
What the error means is that Listbox.ObjectCollection does not have a method or property called ToArray. So, you can't call the ToArray on this collection. It is not clear why you want to do this anyway.
There is no need to cast the ListBox to an array. If you need to know the number of items in the list you can do the following
Dim itemsToMove As Integer = ListBox1.Items.Count
Otherwise that line of code Dim itemsToMove = ListBox1.Items.ToArray() is not necessary. You can simply use
For Each item In ListBox1
Form2.lstP.Items.Add(item)
ListBox1.Items.Remove(item)
Next

Resources