Why stop at SQL 2008? We have clients with SQL 2012...
I guess no reason other than I believe that you would need to connect via the SQL Server Native Client OLE DB provider with your DataSource objects.
Why stop at SQL 2008? We have clients with SQL 2012...
I guess no reason other than I believe that you would need to connect via the SQL Server Native Client OLE DB provider with your DataSource objects.
Unless you have an absolute need to be using SQL Server 2005, I would recommend against installing it and go directly for SQL Server 2008.
You will need to get the VS2008 updates to work with it, but it is nice to work with the new SQL version. Plan on a long update process for the VS2008 installation; their have been many over the years.
Directory.CreateDirectory(x.myCriticalFolder)
-> ok so no final "\" on myCriticalFolder. But then,
Dim path As String = myCriticalFolder & "Locations and Call Types.txt"
Missing the "\" between folder and filename
You could use: IO.Path.Combine(x.myCriticalFolder, "Locations and Call Types.txt")
instead.
Have you tried to use a timer to execute your turn-off code?
Have you added the file as an embedded resource?
i.e. can you type in your code: My.Resources.back_blue ?
If so, you will need to extract it to disk first.
Here is a very crude webbrowser example that maintains two history listes. It may give you some ideas. This example uses datatables instead of a string collection.
Well gee, with such an informative description of the problem, all I can say is you did it wrong.
You got it.
There is nothing hard about adding a column to a datatable. The syntaX is
DataTableVariable.Columns.Add("New Column Name", GetType(String))
But if you prefer to give up on it, oh well.
An easy way to do this is to create a string collectionin My.Settings.
You can add/delete from it like any other list. Set it as the Listbox's DataSource.ListBox1.DataSource = My.Settings.History
Just make sure that user settings is set to automatically save or do it in your code in the form closed event handler.
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
My.Settings.Save()
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
My.Settings.Save()
End Sub
Uhm, did you import the System.Xml namespace like I showed?
That was tested against the file you showed and functions fine.
I don't know about using LINQ for this, but I would do it like this.
using System.Xml;
.
.
.
XmlDocument doc = new XmlDocument();
doc.Load("source.xml");
// if you have the xml in a string use doc.LoadXml(stringvar)
XmlNamespaceManager nsmngr = new XmlNamespaceManager(doc.NameTable);
XmlNodeList results = doc.DocumentElement.SelectNodes("child::result", nsmngr);
foreach (XmlNode result in results)
{
XmlNode namenode = result.SelectSingleNode("name");
XmlNodeList types = result.SelectNodes("type");
foreach (XmlNode type in types)
{
Console.WriteLine(type.InnerText);
}
XmlNode fmtaddress = result.SelectSingleNode("formatted_address");
}
Edit:
@Jim, sorry about this. Didn't mean to step on your toes. I got interrupted while posting and did not think to do a refresh before posting.
**********
No offence intended, but the logic of yours is very confusing. I'm not sure that this is much better. It does pretty much what Jim's did and builds the "where" clause on the fly. I downloaded your db and gave it a quick test and it seemed to work, but the logic is my interpretation of what you are trying to do.
Dim genderclause As String = ""
Dim statusclause As String = ""
'set gender part
If mbox.Checked And fbox.Checked Then
genderclause = "((gender = 'Male') Or (gender = 'Female'))"
Else
If mbox.Checked Then genderclause = "(gender = 'Male')"
If fbox.Checked Then genderclause = "(gender = 'Female')"
End If
'set status part
If rbox.Checked And cbox.Checked Then
statusclause = "((status = 'Regular') Or (status = 'Contractual'))"
Else
If rbox.Checked Then statusclause = "(status = 'Regular')"
If cbox.Checked Then statusclause = "(status = 'Contractual')"
End If
Dim whereclause As String
If genderclause.Length = 0 And statusclause.Length = 0 Then
whereclause = "" ' no filter
Else
whereclause = " where " & If(genderclause.Length = 0, "", genderclause & If(statusclause.Length = 0, "", " AND ")) _
& If(statusclause.Length = 0, "", statusclause)
End If
Try
Using conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\employeedb.mdb;")
conn.Open()
Dim command As New OleDbCommand("select * from employees" & whereclause, conn)
Dim …
So a work associate told my that if I add the Microsoft Word Object Library to my reference a user would be able to strip the word document text and process the data as a new string. It seems I was misinformed. There is no way my company is going to pay the Microsoft Word licensing on the 11 computers I am planning to purchase for this project. Any advice on a work-around?
_
\mc-000\WebFTP\Drawings\LoveCalProcedures\65726210test.doc"
Does the Word Document absolutely need to be stored in the Word 97-2003 "doc" format? If it could be stored in the newer "docx" format, you can use the Open XML SDK 2.0 for Microsoft Office to read the file without any licensing issues.
Retrieving the document text is as simple as:
Dim wpdoc As DocumentFormat.OpenXml.Packaging.WordprocessingDocument = WordprocessingDocument.Open("D:\My Documents\programming.docx", isEditable:=False)
Dim body As DocumentFormat.OpenXml.Wordprocessing.Body = wpdoc.MainDocumentPart.Document.Body
Dim doctext As String = body.InnerText
wpdoc.Close()
Ok, I misunderstood what you were trying to accomplish.
You can add a new column to the source datatable (assuming the datasource is a table) to hold the computed label. Then use this new column as your XValueMember. Depending on the complexity of the logic, you may be able to use an DataColumn Expression to automatically compute the new string. Worse case is to loop through the rows and set the new value.
I am glad that you figured it out.
Now that that is out of the way, I suggest that you modify your code to dispose of the PictureBox image before assigning a new one to it.
If IsNothing(picture) = False Then
If frm.PB1.Image IsNot Nothing Then
frm.PB1.Image.Dispose()
frm.PB1.Image = Nothing
End If
frm.PB1.Image = picture
Else
MsgBox("Picture returned nothing")
End If
This will release the previous image for garbage collection. If you don't your program will continue to use more and more memory.
I am beginning to suspect that the issue is the MDI taskbar that shows up when you maximize a child form. I have attached a simple project for you to play with.
How about just adding a title?
Dim sometitle As New Title()
With sometitle
.Text = "Fred"
.IsDockedInsideChartArea = True
.Docking = Docking.Bottom
.Alignment = ContentAlignment.MiddleCenter
End With
Chart1.Titles.Add(sometitle)
I just had another thought, try moving your maximize code from the Load handler to the Shown handler.
Have you some how set the MaximumSize property to something other than Size.Empty?
Random is a pseudoRandom generator. You are creating a new instance each time. Without checking the docs, I believe it seeds based on system time. Therefore your seed value on differs only a bit on each creation.
Try this:
Private rnd As New Random
Private Sub Me_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Shown
DrawColor(New Rectangle(50, 50, 100, 100))
For i As Int32 = 0 To 20
DrawColor(GimmiRectangle)
Next
End Sub
Private Sub DrawColor(ByVal rNew As Rectangle)
Try
Dim g As Graphics = Me.CreateGraphics
g.DrawRectangle(New Pen(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))), rNew)
g.Dispose()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Function GimmiRectangle() As Rectangle
Try
Dim rect As New Rectangle(rnd.Next(1000), rnd.Next(1000), rnd.Next(1000), rnd.Next(1000))
Return rect
Catch ex As Exception
MsgBox(ex.ToString)
Return New Rectangle(0, 0, 0, 0)
End Try
End Function
Update the underlying datatable directly. This will ensure that the changes are reflected in the dataview.
Something like this:
Public Class Form1
Dim dtSource As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim r As DataRow
With dtSource
.Columns.Add("store", GetType(String))
.Columns.Add("hours", GetType(Double))
r = .NewRow : r(0) = "s1" : r(1) = 3.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s1" : r(1) = 5.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s1" : r(1) = 51.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s1" : r(1) = 13.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s1" : r(1) = 33.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s2" : r(1) = 35.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s2" : r(1) = 54.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s2" : r(1) = 23.0# : .Rows.Add(r)
r = .NewRow : r(0) = "s2" : r(1) = 31.0# : .Rows.Add(r)
.DefaultView.Sort = "[hours] Asc"
End With
DataGridView1.DataSource = dtSource.DefaultView
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
AddhoursToStore("s1", 50.0#)
End Sub
Sub AddhoursToStore(ByVal store As String, ByVal hrsToAdd As Double)
For Each row As DataRow In dtSource.Select("[store] = '" & store & "'")
row("hours") = CType(row("hours"), Double) + hrsToAdd
Next
End Sub
End Class
What did you not understand about the information that I provided you? You still have the issues no matter which method you use to convert the byte array to an image. If the the byte array is null, it will fail.
Here is another option using the FileSystemObject
Sub ListDrives()
Dim fso As Scripting.FileSystemObject 'needs refernce to: Microsoft Scripting Runtime
Dim fsoDrives As Scripting.drives
Set fso = New FileSystemObject
Set fsoDrives = fso.drives
Dim i As Integer
Dim letter As String
Dim driveType As String
For i = Asc("A") To Asc("Z")
letter = Chr$(i)
If fso.DriveExists(letter) Then
Select Case fso.drives(letter).driveType 'returns DriveTypeConst
Case Scripting.UnknownType
driveType = "Unknown"
Case Scripting.Removable
driveType = "Removable"
Case Scripting.Fixed
driveType = "Fixed"
Case Scripting.Remote
driveType = "Remote"
Case Scripting.CDRom
driveType = "CDRom"
Case Scripting.RamDisk
driveType = "RamDisk"
End Select
MsgBox "Drive " & letter & " - " & driveType
End If
Next i
Set fsoDrives = Nothing
Set fso = Nothing
End Sub
The error message indicates that "pictureData" is null (Nothing).
Make sure your query is correct and check for null before converting to an Image.
If pictureData IsNot Nothing Then
Another issue that you may run into using the ExecuteScalar command is the size limit that it can return. From the documentation on the return value:
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters
You may want to consider using a datareader instead and use reader.GetValue(0).
If you are only showing the first column, then I suspect you may not have the ListView configured correctly. I don't use this control very often, but for three columns, I would do it like this:
With ListView1
.View = View.Details
.HeaderStyle = ColumnHeaderStyle.None ' set to whatever you need
.Columns.Clear() ' make sure collumnscollection is empty
' Add 3 columns
.Columns.AddRange(New ColumnHeader() {New ColumnHeader(), New ColumnHeader(), New ColumnHeader()})
End With
To make that work you need to have Option Strict Off which is something I personally do not care for, but to each their own.
You are forcing a narrowing implicit conversion on the method signature (delegate). Based on Variance in Delegates (C# and Visual Basic) I believe you are safe.
@Andre, did you by chance mean to use InstrRev in line 6 of your code?
Here's my entry for this mundane function.
Function RemoveExt(fname As String, Optional extToRemove As String = "") As String
' if extToRemove = "" then all extensions removed
Dim pt_pos As Integer
pt_pos = InStrRev(fname, ".")
If pt_pos <> 0 Then
If extToRemove = "" Then
'Remove all extensions
RemoveExt = Left(fname, pt_pos - 1)
Else
extpart = Right(fname, (Len(fname) - pt_pos) + 1)
If LCase(extpart) = LCase(extToRemove) Then
RemoveExt = Left(fname, pt_pos - 1)
Else
RemoveExt = fname
End If
End If
Else
RemoveExt = fname
End If
End Function
I'm not sure this what you are attempting, but I have assumed:
you want to save the file with "students" sorted on "Day"
Dim doc As New Xml.XmlDocument ' create a XMLDocument to hold the file
doc.Load("SourceFile.xml") ' load the file
' Since Events is your main element it is the "DocumentElement"
Dim Events As Xml.XmlNode = doc.DocumentElement
' add a new "students" element to "Events"
Dim elStudents As Xml.XmlElement = doc.CreateElement("students")
Dim elDay As Xml.XmlElement = doc.CreateElement("Day")
elDay.InnerText = "3"
elStudents.AppendChild(elDay)
Events.AppendChild(elStudents)
' since there are only "students" elements as child nodes of "Events",
' all child nodes are "students"
' we will create a list that can be sorted and load it from "Events.ChildNodes"
Dim sortedstudents As List(Of Xml.XmlElement) = _
(From el In Events.ChildNodes Select CType(el, Xml.XmlElement)).ToList
' I am assuming that "Day" is an Integer;
' therefore, I am converting it to an Integer for comparison during sorting
sortedstudents.Sort(Function(el1 As Xml.XmlElement, el2 As Xml.XmlElement) _
CInt(el1.SelectSingleNode("Day").InnerText).CompareTo( _
CInt(el2.SelectSingleNode("Day").InnerText)))
Events.RemoveAll() ' Delete all exiting child nodes from Events
' now append the sorted "students" elements to the empty "Events" element
For Each el As Xml.XmlElement In sortedstudents
Events.AppendChild(el)
Next
' save the processed file
doc.Save("fred.xml")
Please show a sample of your original xml file. Then manually create and show a sample of how it should look after it has been sorted.
Just a bit of info to add to the discussion.
Your original code will give you your expected result if you changeobjWriter.Write(editor.RichTextBox1.Text)
toobjWriter.Write(editor.RichTextBox1.Rtf)
Those dang computers always try to do what you tell them to do, not what you want them to do. :)
That said, its easier to use the Save and Load methods as Jim has shown you.
Jim has a minor error in his code:
"SELECT * FROM invoiced_filter " & _
" WHERE (Invoiced > #" & fromdte & "# AND Invoiced < #" & todte & "#)"
Access also supports the Between statement but it requires the hash mark ("#") as Jim shown.
"SELECT * FROM invoiced_filter " & _
" WHERE (Invoiced Between #" & fromdte & "# AND Invoiced < #" & todte & "#)"
Give this code pattern a try:
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' When working with ComObjects like a WordApp or any of its parts like Docement, Range etc.
' define a variable for each part.
' I follow the Single Dot Rule when accessing the component classes.
' i.e. donot code doc.BooKmarks("Contact1").Range.Text
' (Bookmark class and Range Class referenced)
'
' This can create unbound references to a ComObject that will cause Word to remain running as
' a hidden application.
Dim wordapp As Word.Application = CType(CreateObject("Word.Application"), Word.Application)
' load a document template file
Dim doc As Word.Document = wordapp.Documents.Add("D:\My Documents\temp\Word Example Bookmark Template.dot")
Dim bookmark As Word.Bookmark = doc.Bookmarks("Contact1")
Dim rng As Word.Range = bookmark.Range
bookmark = Nothing ' done with bookmark, so release it
rng.Text = "some text"
rng = Nothing ' done with this range, so release it
doc.SaveAs("D:\My Documents\temp\Word Example Bookmark Template.doc", Word.WdDocumentType.wdTypeDocument)
doc.Close(False)
doc = Nothing ' done with doc, so release it
wordapp.Quit()
wordapp = Nothing 'done with app, so release it
End Sub
End Class
For you first question regarding Process. "Process.Start" is a shared function that returns the started process. The correct syntax would be:
Dim NewProcess As Process ' No New keyword
If Attachment2TextBox.Text <> "" Then NewProcess = Process.Start(Attachment2TextBox.Text)
For you second question, I am not going to re-invent the wheel, but rather point you to Microsoft's code example on this. It provides a nice description of how to do this.
The root page for their samples is:
deceptikon,
Warning - I'm on my soapbox again
It is not your fault that MS has always tried to make VB.Net compile whatever garbage it is thrown.
"Option Strict" should never have been an option at all, all they needed to do was provide an code attribute syntax to allow late binding for when it is absolutely necessary.
I really hate their Anonymous Type for LINQ "BS" as well with telling people that have to use it for LINQ with "Option Infer ON". That's another option that I loath as I believe in being very explicit when it comes to coding. I really get a kick out of the many VB examples in the documentation that do not hold the company line and show strongly typed LINQ.
Option Explicit On ' declare your variable types
Option Strict On ' no implicit type conversion
Option Infer Off ' inference is just an (hopefully) educated guess as to one's intent.
OK, I'm back on my meds. ;)
Have a nice day.
I believe you are getting the error due to your use of "+" for string concatonation. Since you have a numerical value (cmbSecurity_Ques.SelectedIndex) in your code, the compiler is treating all of it as a mathematical equation.
Switch to using "&" and change:
cmbSecurity_Ques.SelectedIndex
to:
cmbSecurity_Ques.SelectedIndex.ToString
Be advised that setting the class style to CS_NOCLOSE (named CP_NOCLOSE_BUTTON in Doogledude's example) will also prevent Alt-F4 from closing the window. You can achieve the same effect while retaining Alt-F4 closure by PInvoking the RemoveMenu function.
Private Const MF_BYCOMMAND As Integer = 0
<DllImport("User32")> _
Private Shared Function RemoveMenu(ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Integer) As Integer
End Function
<DllImport("User32")> _
Private Shared Function GetSystemMenu(ByVal hWnd As IntPtr, ByVal bRevert As Boolean) As IntPtr
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim hMenu As IntPtr = GetSystemMenu(Me.Handle, False)
RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND)
End Sub
You need an ExpandableObjectConverter.
It's pretty easy to do. :)
Here is the converter:
Public Class DatabasePropertiesConverter
Inherits ExpandableObjectConverter
Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As Globalization.CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object
If destinationType Is GetType(String) Then
Return "" ' this prevents the type name from showing up in the property grid
End If
Return MyBase.ConvertTo(context, culture, value, destinationType)
End Function
End Class
Now to implement it
<TypeConverter(GetType(DatabasePropertiesConverter))> _
Public Class DatabaseProperties
.
. <ommitted code>
.
'add the NotifyParentPropertyAttribute to each sub property
<NotifyParentProperty(True)> _
<Category("Connection")> _
<Description("Host Name/IP address of the server where the database resides.")> _
<DefaultValue(GetType(String), "")> _
<DisplayName("Host Address")> _
<Browsable(True)> _
<ReadOnlyAttribute(False)> _
Public Property HostName() As String
Get
Return Me.DBHost
End Get
Set(ByVal value As String)
Me.DBHost = value
End Set
End Property
. **** I corrected the above property from DBUser to DBHost
.
. <do same for other properties>
.
I don't use either VS2012 or MySql, but based on their support forum, it looks like a lot of people have had issues with this configuration. Do you have the the latest vesion of Connector/Net installed? Based on this: Click Here, the newer releases should offer full VS2012 support.
As a possible workaround, have you tried connecting through ODBC instead?
Perhaps use a checkbox with a button appearance instead?
Public Class Form1
Private WithEvents chkButton As New CheckBox _
With {.Appearance = Appearance.Button, _
.CheckState = CheckState.Unchecked, _
.Location = New Point(10, 10), _
.Size = New Size(150, 25), _
.TextAlign = ContentAlignment.MiddleCenter, _
.Text = "I'm really a checkbox", _
.Parent = Me}
Private Sub chkButton_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkButton.CheckedChanged
If chkButton.Checked Then
MsgBox("I'm Depressed")
Else
MsgBox("I'm Up")
End If
End Sub
End Class
Perhaps using a TimeSpan instead of a DateTime will give you the effect you are looking for?
Public Class Form1
Private WithEvents tmCountDown As New System.Windows.Forms.Timer With {.Interval = 1000}
Private tsStartTime As TimeSpan
Private lblCountDown As New Label With {.Location = New Point(10, 10), _
.AutoSize = True, _
.Font = New Font("Deja Vu Sans", 14, FontStyle.Regular, GraphicsUnit.Point), _
.ForeColor = SystemColors.WindowText, _
.TextAlign = ContentAlignment.MiddleCenter, _
.Parent = Me}
Private OneSecond As New TimeSpan(0, 0, 1)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set these durations to whatever is needed
Dim Days As Int32 = 0
Dim Hrs As Int32 = 0
Dim Mins As Int32 = 0
Dim Secs As Int32 = 1
Dim MilliSecs As Int32 = 0
tsStartTime = New TimeSpan(Days, Hrs, Mins, Secs, MilliSecs)
DisplayTime()
tmCountDown.Start()
End Sub
Private Sub tmCountDown_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmCountDown.Tick
tsStartTime = tsStartTime.Subtract(OneSecond)
DisplayTime()
' Stop CountDown ? If so, uncomment next line
'If tsStartTime.Ticks = 0 Then tmCountDown.Stop()
End Sub
Private Sub DisplayTime()
If tsStartTime.Ticks < 0 Then
lblCountDown.BackColor = Color.Yellow
Else
lblCountDown.BackColor = SystemColors.Window
End If
lblCountDown.Text = tsStartTime.ToString.Replace("."c, ":"c)
End Sub
End Class
Is the button a Microsoft Forms 2.0 Object Library CommandButton that has a TakeFocusOnClick property? If so, try setting the property to false.
Perhaps something like this:
' Since all your items are then same, create a list to use as a common DataSource for each ComboBox
Dim items() As String = {"Sample 1", "Sample 2", "Sample 3", "Sample 4"}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Since your ComboBoxes are named in a consecutive pattern, we can look up their names in a loop
Dim cboName As String = String.Empty
Dim p As Control
For i As Int32 = 1 To 40
cboName = "ComboBox" & i.ToString
p = FindParent(Me, cboName)
If p IsNot Nothing Then
CType(p.Controls(cboName), ComboBox).DataSource = items
End If
Next
End Sub
' Since the ComboBoxes may be parented in a child control, we need to identify their parent control
' a simple recursive search will do the trick
Private Function FindParent(ByVal source As Control, ByVal name As String) As Control
For Each c As Control In source.Controls
If c.Name = name Then
If c.Parent IsNot Nothing Then
Return c.Parent
Else
Return source
End If
Else
If c.HasChildren Then
Dim parent As Control = FindParent(c, name)
If parent IsNot Nothing Then Return parent
End If 'c.HasChildren
End If 'c.Name = name
Next
Return Nothing
End Function
If by "The thread is running in a module" you mean that the method being executed is in a Module, a similar technique can be used. Here is a slightly different version executing a method defined in a module.
Public Class Form1
Private myParameterInstance As MyParameter
Dim thrd As Threading.Thread
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
thrd = New Threading.Thread(AddressOf Something.threadMethod)
myParameterInstance = New MyParameter(New MethodInvoker(AddressOf ToggleForm2))
thrd.Start(myParameterInstance)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
myParameterInstance.Cancel = True
End Sub
Private Sub ToggleForm2()
If Me.InvokeRequired Then
' on other thread so call on UI thread
Me.Invoke(New MethodInvoker(AddressOf ToggleForm2))
Exit Sub ' on non UI thread
End If
Form2.Visible = Not Form2.Visible
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
' Clean up
If myParameterInstance IsNot Nothing Then
myParameterInstance.Cancel = True 'shut the thread down
While thrd.IsAlive
Threading.Thread.Sleep(500)
Debug.WriteLine("waiting to end")
End While
End If
End Sub
End Class
' Define a parameter class that contains the info to be passed to the threaded method
' You could just pass a MethodInvoker instance, but I like having a way to cancel a thread
' so I use a Class with a Cancel Property
Friend Class MyParameter
Public mi As MethodInvoker 'use a simple MethodInvoker to execute a UI method
Public Sub New(ByVal mi As MethodInvoker)
Me.mi = mi
End Sub
Private _Cancel As Boolean
Public Property Cancel() As Boolean
Get
Return …
I'm not sure I understand your situation correctly, but UI controls must be manipulated only on the thread that created them. Here is an example that flashes Form2. Note the pattern used with the InvokeRequired.
Public Class Form1
Private WithEvents bgw As New System.ComponentModel.BackgroundWorker With {.WorkerSupportsCancellation = True}
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
bgw.RunWorkerAsync()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
bgw.CancelAsync() ' cancel backgroundworker
End Sub
Private Sub ToggleForm2()
If Me.InvokeRequired Then
' on other thread so call on UI thread
Me.Invoke(New MethodInvoker(AddressOf ToggleForm2))
Exit Sub ' on non UI thread
End If
Form2.Visible = Not Form2.Visible
End Sub
Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
Do
If bgw.CancellationPending Then
e.Cancel = True
Exit Do
End If
ToggleForm2()
Threading.Thread.Sleep(1000)
Loop
End Sub
End Class
That is not a question, that is a specification. As stated above, show what you have tried and described what is giving you problems.
Give this a try:
Remember that the column nubering is zero index based (Column4 = index 3)
Dim sum As Int32 = (From dgvrow In DataGridView1.Rows _
Select CInt(CType(dgvrow, DataGridViewRow).Cells(3).Value)) _
.Sum()