I facing problem in my login system.
This is my coding: I already add reference MySQL.Data in my form.When i click the button,this error message is showed. (A first chance exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll).
Imports MySql.Data.MySqlClient
Public Class Form1
Public conn As MySqlConnection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost; user id=root; password=; database=test")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM yy WHERE Username = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
MsgBox("Login")
Else
MsgBox("Failed Login")
End If
Else
MsgBox("Failed Login")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
Related
Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;"
Dim dbSource As String = "Data Source=D:\Visual Basic\dito\Database2.accdb;"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = dbProvider & dbSource
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox3.Text = Nothing Or TextBox4.Text = Nothing Then
MessageBox.Show("Please enter details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If con.State = ConnectionState.Closed Then
con.Open()
End If
Using cmd As New OleDbCommand("SELECT COUNT(*)FROM member WHERE [USERNAME] = #USERNAME OR [PASSWORD] = #PASSWORD", con)
cmd.Parameters.AddWithValue("#USERNAME", OleDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.AddWithValue("#PASSWORD", OleDbType.VarChar).Value = TextBox4.Text
Dim count = Convert.ToInt32(cmd.ExecuteScalar())
If count > 0 Then
MessageBox.Show("oops, username and password has already been taken", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
End Using
Using create As New OleDbCommand("INSERT INTO member(USERNAME], [PASSWORD])VALUES(#USERNAME,PASSWORD)")
create.Parameters.AddWithValue("#USERNAME", OleDbType.VarChar).Value = TextBox3.Text
create.Parameters.AddWithValue("#PASSWORD", OleDbType.VarChar).Value = TextBox4.Text
If create.ExecuteNonQuery Then
MessageBox.Show("Account created", "information", MessageBoxButtons.OK, MessageBoxIcon.Information)
TextBox3.Clear()
TextBox4.Clear()
End If
End Using
con.Close()
End Sub
End Class
pls help dont know what to do
I designed a Form and it use to the sub Form
The Mainform is correctly display, but I use some action to show the sub Form and set Visible property of Mainform to false
The sub Form is displayed incorrectly
^^ Sub Form
^^ displayed
MainForm code:
Imports SearcherScreen = Osu_Offline_Searcher.My.SearcherScreen
Public Class SearcherOfOsu
Private ReadOnly SS As New SearcherScreen()
Private ReadOnly DOF As New DownloadOsuForm()
Private Sub Downloader_OnDownloadData(sender As OsuDownload.OsuDownloader, e As OsuDownload.OsuDownloader.DownloadDataEventArgs) Handles Downloader.DownloadData
If DOF.Created Then
DOF.ChangeProgressBar(e.Present)
Else
DOF.Icon = New Icon("osu!.ico")
DOF.Show()
Visible = False
End If
End Sub
Private Sub DetectButton_Click(sender As Object, e As EventArgs) Handles DetectButton.Click
Dim Detecter As New OsuDetect.DetectClass()
Dim UserDirectoryName = Detecter.DetectUserDirectory()
If UserDirectoryName = "No User" Then
MsgBox("I can't find any User.")
Else
Dim OsuDirectoryName = Detecter.DetectOsuDirectory(UserDirectoryName)
If OsuDirectoryName = "No Osu" Then
MsgBox("You don't download the Osu in defalut directory.")
Dim Result = MsgBox("Download Osu now?", MsgBoxStyle.YesNo, "Download Osu")
If Result = MsgBoxResult.Yes Then
OsuDirectoryPath.Text = Downloader.DownloadOsu(UserDirectoryName)
Visible = True
DOF.Close()
End If
Else
OsuDirectoryPath.Text = OsuDirectoryName
End If
End If
End Sub
Friend WithEvents Downloader As New OsuDownload.OsuDownloader()
End Class
Sub Form:
Public Class DownloadOsuForm
Sub ChangeProgressBar(Value As Integer)
OsuDownloadProgressBar.Value = Value
OsuDownloadLabel.Text = "Osu Downloading..."
End Sub
End Class
This the code of forms
and after here is the designer code
Sub Designer Code:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class DownloadOsuForm
Inherits System.Windows.Forms.Form
'Form 覆寫 Dispose 以清除元件清單。
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'為 Windows Form 設計工具的必要項
Private components As System.ComponentModel.IContainer
'注意: 以下為 Windows Form 設計工具所需的程序
'可以使用 Windows Form 設計工具進行修改。
'請勿使用程式碼編輯器進行修改。
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.OsuDownloadProgressBar = New System.Windows.Forms.ProgressBar()
Me.OsuDownloadLabel = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'OsuDownloadProgressBar
'
Me.OsuDownloadProgressBar.Location = New System.Drawing.Point(60, 205)
Me.OsuDownloadProgressBar.Minimum = 0
Me.OsuDownloadProgressBar.Maximum = 100
Me.OsuDownloadProgressBar.Value = 0
Me.OsuDownloadProgressBar.Name = "OsuDownloadProgressBar"
Me.OsuDownloadProgressBar.Size = New System.Drawing.Size(280, 30)
Me.OsuDownloadProgressBar.TabIndex = 0
'
'OsuDownloadLabel
'
Me.OsuDownloadLabel.AutoSize = True
Me.OsuDownloadLabel.Font = New System.Drawing.Font("新細明體", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.OsuDownloadLabel.Location = New System.Drawing.Point(105, 155)
Me.OsuDownloadLabel.Name = "OsuDownloadLabel"
Me.OsuDownloadLabel.Size = New System.Drawing.Size(190, 24)
Me.OsuDownloadLabel.TabIndex = 1
Me.OsuDownloadLabel.Text = "Osu Downloading..."
'
'DownloadOsuForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(9.0!, 18.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(400, 400)
Me.Controls.Add(Me.OsuDownloadLabel)
Me.Controls.Add(Me.OsuDownloadProgressBar)
Me.Margin = New System.Windows.Forms.Padding(1, 3, 1, 3)
Me.Name = "DownloadOsuForm"
Me.Text = "Downloading Osu"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents OsuDownloadProgressBar As ProgressBar
Friend WithEvents OsuDownloadLabel As Label
End Class
so this code works with just the out parameter but then when you add in parameters weird nulls start showing up and also the straight in parameters work too so it is just when there are both in and out parameters.
the part with problems is the in and out parameters do not want to coexist
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
For Each kvp As KeyValuePair(Of String, String) In sqlParams
Dim newParam As New OracleParameter(kvp.Key, OracleDbType.Varchar2, kvp.Value, Data.ParameterDirection.Output)
newParam.Size = 400
cmd.Parameters.Add(newParam)
Next
This works
Public Shared Sub Run_Oracle_Query(ByVal queryToRun As String, ByVal sqlParams As Dictionary(Of String, String))
Dim dbConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ITSS").ConnectionString
Dim con As OracleConnection = New OracleConnection(dbConnString)
Dim cmd = con.CreateCommand()
Try
con.Open()
cmd.CommandText = queryToRun
cmd.CommandType = CommandType.Text
For Each kvp As KeyValuePair(Of String, String) In sqlParams
cmd.Parameters.Add(kvp.Key, kvp.Value)
Next
cmd.ExecuteNonQuery()
'log all sql queryies very expensive operation
LogThisString("Log All queries: " & queryToRun, "Always")
Catch ex As OracleException ' catches only Oracle errors
OracleExceptionLogging(ex.Number, queryToRun, ex)
Catch ex As Exception
LogThisString("General Error SQL: " + ex.Message.ToString(), "Always")
' MsgBox("Could Not Perform This Database Operation")
Finally
con.Close()
cmd.Dispose()
con.Dispose()
End Try
End Sub
This works
Public Shared Function Run_Insert_Oracle_Query_Return_ID(ByVal queryToRun As String, ByVal IDcolumnName As String) As String
Dim dbConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ITSS").ConnectionString
Dim con As OracleConnection = New OracleConnection(dbConnString)
Dim cmd = con.CreateCommand()
Dim strUkey As String = ""
Try
con.Open()
cmd.CommandText = queryToRun & " RETURNING " & IDcolumnName & " INTO :UKEY"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
cmd.ExecuteNonQuery()
strUkey = cmd.Parameters("PKEY").Value.ToString
Return strUkey
Catch ex As OracleException ' catches only Oracle errors
OracleExceptionLogging(ex.Number, queryToRun, ex)
Catch ex As Exception
LogThisString("General Error SQL: " + ex.Message.ToString(), "Always")
PopupMsgBox("Database Error", "Database Integrity Constants Violated SQL Operation Will Not Be Executed")
Finally
con.Close()
cmd.Dispose()
con.Dispose()
End Try
Return strUkey
End Function
This does not work
Public Shared Function Run_Insert_Oracle_Query_Return_ID(ByVal queryToRun As String, ByVal IDcolumnName As String, ByVal sqlParams As Dictionary(Of String, String)) As String
Dim dbConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ITSS").ConnectionString
Dim con As OracleConnection = New OracleConnection(dbConnString)
Dim cmd = con.CreateCommand()
Dim strUkey As String = ""
Try
con.Open()
cmd.CommandText = queryToRun & " RETURNING " & IDcolumnName & " INTO :UKEY"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
For Each kvp As KeyValuePair(Of String, String) In sqlParams
Dim newParam As New OracleParameter(kvp.Key, OracleDbType.Varchar2, kvp.Value, Data.ParameterDirection.Output)
newParam.Size = 400
cmd.Parameters.Add(newParam)
Next
cmd.ExecuteNonQuery()
strUkey = cmd.Parameters("PKEY").Value.ToString
Return strUkey
Catch ex As OracleException ' catches only Oracle errors
OracleExceptionLogging(ex.Number, queryToRun, ex)
Catch ex As Exception
LogThisString("General Error SQL: " + ex.Message.ToString(), "Always")
PopupMsgBox("Database Error", "Database Integrity Constants Violated SQL Operation Will Not Be Executed")
Finally
con.Close()
cmd.Dispose()
con.Dispose()
End Try
Return strUkey
End Function
crap so i guess it does look for order asnd the output does need to be at end like this.....this works solved my own problem
For Each kvp As KeyValuePair(Of String, String) In sqlParams
Dim newParam As New OracleParameter(kvp.Key, OracleDbType.Varchar2, kvp.Value, Data.ParameterDirection.Input)
newParam.Size = 400
cmd.Parameters.Add(newParam)
Next
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
I found a script online to copy some files whilst also displaying a progress bar to the user. I wondered if it was possible to automate this process so the file copy initiates as soon as the program launches and then closes once completed. VB is not my strong point as I usually code in c sharp. Any help much appreciated.
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.IO
Public Class Form1
'--- Class to report progress
Private Class UIProgress
Public Sub New(ByVal name_ As String, ByVal bytes_ As Long, ByVal maxbytes_ As Long)
name = name_ : bytes = bytes_ : maxbytes = maxbytes_
End Sub
Public name As String
Public bytes As Long
Public maxbytes As Long
End Class
'--- Class to report exception
Private Class UIError
Public Sub New(ByVal ex As Exception, ByVal path_ As String)
msg = ex.Message : path = path_ : result = DialogResult.Cancel
End Sub
Public msg As String
Public path As String
Public result As DialogResult
End Class
'--- Members
Private mCopier As New BackgroundWorker
Private Delegate Sub ProgressChanged(ByVal info As UIProgress)
Private Delegate Sub CopyError(ByVal err As UIError)
Private OnChange As ProgressChanged
Private OnError As CopyError
Public Sub New()
InitializeComponent()
AddHandler mCopier.DoWork, AddressOf Copier_DoWork
AddHandler mCopier.RunWorkerCompleted, AddressOf Copier_RunWorkerCompleted
mCopier.WorkerSupportsCancellation = False
OnChange = AddressOf Copier_ProgressChanged
OnError = AddressOf Copier_Error
ChangeUI(False)
mCopier.RunWorkerAsync()
End Sub
Private Sub Copier_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
'--- Create list of files to copy
Dim theExtensions As String() = {"*.jpg", "*.jpeg", "*.bmp", "*.png", "*.gif"}
Dim files As New List(Of FileInfo)
Dim path As String = "c:\users\simon\desktop\b\"
Dim dir As New DirectoryInfo(path)
Dim maxbytes As Long = 0
For Each ext As String In theExtensions
Dim folder As FileInfo() = dir.GetFiles(ext, SearchOption.AllDirectories)
For Each file As FileInfo In folder
If ((file.Attributes And FileAttributes.Directory) <> 0) Then Continue For
files.Add(file)
maxbytes += file.Length
Next
Next
'--- Copy files
Dim bytes As Long = 0
For Each file As FileInfo In files
Try
Me.BeginInvoke(OnChange, New Object() {New UIProgress(file.Name, bytes, maxbytes)})
System.IO.File.Copy(file.FullName, "C:\Users\Simon\Desktop\t\" + file.Name, True)
Catch ex As Exception
Dim err As New UIError(ex, file.FullName)
Me.Invoke(OnError, New Object() {err})
If err.result = DialogResult.Cancel Then Exit For
End Try
bytes += file.Length
Next
End Sub
Private Sub Copier_ProgressChanged(ByVal info As UIProgress)
'--- Update progress
ProgressBar1.Value = CInt(100.0 * info.bytes / info.maxbytes)
Label1.Text = "Copying " + info.name
End Sub
Private Sub Copier_Error(ByVal err As UIError)
'--- Error handler
Dim msg As String = String.Format("Error copying file {0}\n{1}\nClick OK to continue copying files", Err.path, Err.msg)
err.result = MessageBox.Show(msg, "Copy error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
End Sub
Private Sub Copier_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
'--- Operation completed, update UI
ChangeUI(False)
End Sub
Private Sub ChangeUI(ByVal docopy As Boolean)
Label1.Visible = docopy
ProgressBar1.Visible = docopy
If docopy Then Button1.Enabled = False Else Button1.Text = "Copy"
Label1.Text = "Starting copy..."
ProgressBar1.Value = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim docopy As Boolean = Button1.Text = "Copy"
ChangeUI(docopy)
If (docopy) Then mCopier.RunWorkerAsync() Else mCopier.CancelAsync()
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
End Sub
End Class
Just move the code that you have in Button1_Click into the Form_Load event.
Or, alternatively, you could just call the Button1_Click routine from the Form_Load.
Also, FYI, some VB.net tips for C# programmers:
you generally don't need to do the dynamic AddHandler setups in VB.net
This dynamic setup is usually replaced by the static Handles clause of the method declarations, which is auto-generated for you if you use the IDE Control/Event drop-downs
you probably do need "Private With Events ..." for your BackgroundWorker declaration.
Why not convert the code to C#?
http://www.developerfusion.com/tools/convert/vb-to-csharp/
http://converter.telerik.com/
http://codeconverter.sharpdevelop.net/SnippetConverter.aspx
http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx
I have a Winforms application and a combobox has it's datasource set to a DataTable when the form loads. The data displays fine in the combobox.
Then after a user clicks a button I want to create a new DataTable and assign that datatable as the datasource for the combobox.
The problem is that after setting the datasource to be the new datatable the items in the combobox don't change. Here is the code I'm using.
dlCustomer.DataSource = Nothing
dlCustomer.DataSource = dtCustomers
dlCustomer.DisplayMember = "Name"
dlCustomer.Refresh()
Does anyone know how to make the correct data be displayed in the combobox the second time I assign the data source for it?
It should work, at least it did in a quick test I threw together. Here's the code; it just expects a Form with a ComboBox and Button:
Public Class Form1
Private dtOne As DataTable
Private dtTwo As DataTable
Private Sub InitializeTables()
dtOne = New DataTable("TableOne")
With dtOne
.Columns.Add("Text", GetType(String))
.Columns.Add("Value", GetType(Integer))
End With
dtTwo = New DataTable("TableTwo")
With dtTwo
.Columns.Add("Text", GetType(String))
.Columns.Add("Value", GetType(Integer))
End With
Dim newRow As DataRow
For index As Integer = 0 To 2
newRow = dtOne.NewRow
newRow.ItemArray = (New Object() {SpellIt(index), index})
dtOne.Rows.Add(newRow)
Next
For index As Integer = 2 To 0 Step -1
newRow = dtTwo.NewRow
newRow.ItemArray = (New Object() {SpellIt(index), index})
dtTwo.Rows.Add(newRow)
Next
dtOne.AcceptChanges()
dtTwo.AcceptChanges()
End Sub
Private Shared Function SpellIt(ByVal int As Integer) As String
Select Case int
Case 0 : Return "Zero"
Case 1 : Return "One"
Case 2 : Return "Two"
Case Else : Throw New ArgumentOutOfRangeException("Bleh!")
End Select
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
InitializeTables()
Me.Label1.DataBindings.Add("Text", ComboBox1, "SelectedValue")
Me.ComboBox1.DataSource = dtOne
Me.ComboBox1.DisplayMember = "Text"
Me.ComboBox1.ValueMember = "Value"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.ComboBox1.DataBindings.Clear()
Me.ComboBox1.DataSource = Nothing
Me.ComboBox1.DataSource = dtTwo
Me.ComboBox1.DisplayMember = "Text"
Me.ComboBox1.ValueMember = "Value"
End Sub
End Class