I have a .NET project that includes an UltraWinGrid to display data from a database table. On the form with the UWG, I have 3 buttons; 'New Data', 'Edit Data' and 'Delete Data'. The first two open new forms with controls through which to enter/edit the data to be saved. The save function works fine, however when I close the form to see the initial form (with the UWG), the data has not refreshed, and only does so when I close and re-open it.
So, is there any way that I can make the UWG refresh when I press the save button on the new form? (I have already tried calling the function again which loads the UWG, but this doesn't work as I cannot make it a Shared method due to the connections)
Save function code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim m_cn As New OleDbConnection
m_cn = m_database.getConnection()
If txtFirstName.Text = "" Then
MsgBox("First name cannot be blank")
ElseIf txtLastName.Text = "" Then
MsgBox("Last name cannot be blank")
ElseIf txtAge.Text = "" Then
MsgBox("Age cannot be blank")
ElseIf txtPostCode.Text = "" Then
MsgBox("Postcode cannot be blank")
Else
Dim personID As Integer = database.SaveNewPerson(txtFirstName.Text, txtLastName.Text, txtAge.Text, txtPostCode.Text, m_cn)
MsgBox("Save successful")
txtFirstName.Text = ""
txtLastName.Text = ""
txtAge.Text = ""
txtPostCode.Text = ""
End If
End Sub
Code that loads the UWG:
Public Sub getPeople()
Try
Dim sql As String = "SELECT * FROM tblPerson"
Dim cm As New OleDbCommand(sql, m_database.getConnection())
Dim da As New OleDbDataAdapter(cm)
Dim dt As New DataTable()
da.Fill(dt)
ugData.DataSource = dt
Catch Ex As Exception
MsgBox("Could not load people")
End Try
End Sub
You should call the getPeople function in the calling form, not in the saving form.
You just need to know if the saving form has terminated correctly or not and this information is available as the return value for the call to ShowDialog. Your button that saves the person data should have the DialogResult property set to OK and then this code should work for you
' Open the form that inserts a new person
' Change that name to your actual form class name...
Using fp = new frmPerson()
' If the user presses the button to save and everything goes well
' we get the DialogResult property from the button pressed
if fp.ShowDialog() = DialogResult.OK Then
ugData.DataSource = Nothing
getPeople()
End If
End Using
Notice the point if all goes well. This means that if, in your button save procedure something does not go well, you should block the form closing changing the DialogResult property to None.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim m_cn As New OleDbConnection
m_cn = m_database.getConnection()
If txtFirstName.Text = "" Then
MsgBox("First name cannot be blank")
Me.DialogResult = DialogResult.None
ElseIf txtLastName.Text = "" Then
MsgBox("Last name cannot be blank")
Me.DialogResult = DialogResult.None
ElseIf txtAge.Text = "" Then
MsgBox("Age cannot be blank")
Me.DialogResult = DialogResult.None
ElseIf txtPostCode.Text = "" Then
MsgBox("Postcode cannot be blank")
Me.DialogResult = DialogResult.None
Else
Dim personID As Integer = database.SaveNewPerson(txtFirstName.Text, txtLastName.Text, txtAge.Text, txtPostCode.Text, m_cn)
MsgBox("Save successful")
txtFirstName.Text = ""
txtLastName.Text = ""
txtAge.Text = ""
txtPostCode.Text = ""
End If
End Sub
Related
The code below works as intended in DEBUG with no errors. I input my search parameters, the record returns and populates all textboxes and loads the PDF file into the AxAcroPDF1 viewer.
However, after I compile and install the program I am receiving the error "Access to the path 'C:\Program Files (x86)\NAME OF PROGRAM\temp.file' is denied'
This only occurs when I search for a record and the PDF (in Binary format in the DB) to that record is supposed to load fails with the error message listed above. How can I resolve the permissions level (assuming this is the issue) to allow for the PDF to load? The area of concern presumably and more specifically is the LoadPDF() sub.
My code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
'Loads last record on to form
DocumentsTableBindingSource.Position = DocDataset.Documents_Table.Rows.Count - 1
DV = New DataView(DocDataset.Documents_Table)
'LoadPDF()
End Sub
Private Sub BtnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
tbRecNumb.Clear()
tbFileName.Clear()
tbPetsLoadNumber.Clear()
tbBrokerLoadNumber.Clear()
tbFilePath.Clear()
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
' Search for PETS Load Number, Broker Load Numberthen load record if found
Private Sub BtnSearchBtn_MouseEnter(sender As Object, e As EventArgs) Handles btnSearch.MouseEnter
Cursor = Cursors.Hand
btnSearch.BackgroundImage = My.Resources.ButtonDwn_Teal_Trans
End Sub
Private Sub BtnSearchBtn_MouseLeave(sender As Object, e As EventArgs) Handles btnSearch.MouseLeave
Cursor = Cursors.Default
btnSearch.BackgroundImage = My.Resources.Button_Teal_Trans
End Sub
Private Sub TbSearchInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbSearchInput.KeyDown
Cursor = Cursors.Hand
If e.KeyCode = Keys.Enter Then
Search()
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.BackgroundImage = My.Resources.ButtonClk_Teal_Trans
Cursor = Cursors.Hand
Search()
End Sub
Private Sub Search()
Cursor = Cursors.WaitCursor
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
LoadPDF()
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
Cursor = Cursors.Default
End Sub
Private Sub LblSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub LoadPDF()
Dim temp = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User)
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT DOCUMENTS FROM Documents_Table WHERE PETS_LOAD_NUMBER = #pl"
cmd.Parameters.AddWithValue("#pl", tbPetsLoadNumber.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
Dim Buffer As Byte()
cmd.Connection.Open()
Buffer = cmd.ExecuteScalar
cmd.Connection.Close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = Application.StartupPath() & "\temp.file"
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, DOCUMENTS)
VALUES (#bl, #fn, #pl, #pdf)"
cmd.Parameters.Add("#fn", SqlDbType.NVarChar, 50).Value = tbFileName.Text
cmd.Parameters.Add("#pl", SqlDbType.Int).Value = tbPetsLoadNumber.Text
cmd.Parameters.Add("#bl", SqlDbType.NVarChar, 20).Value = tbBrokerLoadNumber.Text
cmd.Parameters.Add("#pdf", SqlDbType.VarBinary, -1).Value = data
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File Successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
In your function LoadPDF you create a reference to tempdir and then don't use it. Instead, you use Application.StartupPath() which will point to C:\Programs(x86) and is usually not writeable without admin rights.
But why don't you use your temp dir:
Dim temp = SpecialDirectories.Temp 'more robust approach to get tempdir
If File.Exists(temp & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(temp & "\temp.file")
End If
...
File.WriteAllBytes(temp & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = temp & "\temp.file"
I have what I believe to be a small oddity in my code. I have a textbox (txtEmail) that get text added to it via code: txtEmail.Text = "Text Here" If I don't tab through the text box before I try to save the record, the text is lost when executing the DataTable.AcceptChanges.
I have tested this by:
Not tabbing through the textboxes - Text gets lost
Tabbing through the textboxes- Text is committed
"Selecting" the textbox via code, then selecting another textbox - Text is commited
Is there something I am missing? Is there any way I can commit the text without selecting or tabbing through the textboxes?
For reference, the textboxes are bound to a binding source, who's DataSource is a DataTable.
Some snippets of code to maybe help...
Filling DA and DT, setting BS:
Using SQLcmd As New SqlCommand With {
.Connection = Vars.sqlConn,
.CommandText = "SELECT * FROM [Database].[Table]"}
da_Users.SelectCommand = SQLcmd
Dim sqlCB As New SqlCommandBuilder(da_Users)
AddHandler da_Users.RowUpdated, AddressOf OnRowUpdated
da_Users.Fill(dt_Users)
dt_Users.Columns("Active").DefaultValue = True
dt_Users.Columns("Phone").DefaultValue = "6-1800, ()"
bs_Users.DataSource = dt_Users
bsnav_Users.BindingSource = bs_Users
End Using
Updating Email Textbox
Private Sub txtName_Leave(sender As Object, e As EventArgs) Handles txtLastName.Leave, txtFirstName.Leave
Try
Dim tb As TextBox = DirectCast(sender, TextBox)
tb.Text = StrConv(tb.Text, VbStrConv.ProperCase)
If Not txtFirstName.Text = "" And Not txtLastName.Text = "" Then
Dim strFNames() = txtFirstName.Text.Trim.Split(New Char() {" "c})
Dim strLNames() = txtLastName.Text.Trim.Split(New Char() {" "c})
txtEmail.Text = strLNames(0) & "." & strFNames(0) & "#sample.com"
End If
Catch ex As Exception
CustExErrorMsg(Name, Reflection.MethodBase.GetCurrentMethod().Name, GetExceptionInfo(ex))
End Try
End Sub
Saving the record:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles BNavSaveItem.Click
Try
If IsComplete() Then
If blnNew Then If IsDuplicate() Then Exit Sub
lblTSS.Text = "Saving..."
lblTSS.BackColor = Color.IndianRed
Application.DoEvents()
'Added to commit text
txtEmail.Select()
txtFirstName.Select()
Me.Validate()
If blnNew Then dt_Users.AcceptChanges()
bs_Users.EndEdit()
da_Users.Update(dt_Users)
lblTSS.Text = "Done"
lblTSS.BackColor = Color.LightGreen
End If
Catch SqlExceptionErr As SqlException
CustSQLErrorMsg(Name, System.Reflection.MethodBase.GetCurrentMethod().Name, SqlExceptionErr.Message)
Catch ex As Exception
CustExErrorMsg(Name, Reflection.MethodBase.GetCurrentMethod().Name, GetExceptionInfo(ex))
End Try
End Sub
I'm pretty sure this code used to allow me to login using the SQL statement below, but now it doesn't and just clears the text boxes.
There is also an error message that I would like displayed when the username and password do not match that in the database. This is, like the other one, a label that the visibility would need changing. I had this code:
Try
UserType = GetUserType(txtUsername.Text.Trim, txtPass.Text.Trim)
Catch ex As Exception
lblErrorMatch.Visible = True
End Try
However, this just clears the text boxes when the details do not match.
Imports System.Data.OleDb
Public Class frmLogin
Private DBCmd As New OleDbCommand
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;"
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim UserType As Object
'Distinguishing beetween different users
If UserType Is Nothing Then
lblErrorEmpty.Visible = True
ElseIf UserType.ToString = "MANAGER" Then
frmHomeManager.Show()
ElseIf UserType.ToString = "RECEPTIONIST" Then
frmHomeReceptionist.Show()
End If
'Username and password not matching error message
'Empty textboxes error message
If txtUsername.Text = "" OrElse txtPass.Text = "" Then lblErrorEmpty.Visible = True : Exit Sub
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Function GetUserType(Username As String, Pass As String) As Object
Dim UserType As Object
'Pull username and password from the database to check against the entered login details
Using DBCon As New OleDb.OleDbConnection(ConStr),
DBCmd As New OleDbCommand("SELECT UserType FROM tblEmployeeLogin WHERE [Username] = #Username AND [Pass] = #Pass", DBCon)
DBCmd.Parameters.Add("#Username", OleDbType.VarChar).Value = Username
DBCmd.Parameters.Add("#Pass", OleDbType.VarChar).Value = Pass
DBCon.Open()
UserType = DBCmd.ExecuteScalar.ToString
End Using
Return UserType
End Function
Private Sub chkShowPass_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPass.CheckedChanged
'Show password when checkbox is checked
If chkShowPass.Checked = True Then
txtPass.PasswordChar = Nothing
ElseIf chkShowPass.Checked = False Then
txtPass.PasswordChar = "*"
End If
End Sub
Private Sub txtUsername_TextChanged(sender As Object, e As EventArgs) Handles txtUsername.TextChanged, txtPass.TextChanged
'Make error message disappear after text is enetered into either of the text boxes
lblErrorEmpty.Visible = False
lblErrorMatch.Visible = False
End Sub
Private Sub lnkClear_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lnkClear.LinkClicked
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
'Close the form down which stops the application
Me.Close()
End Sub
End Class
Thank you for your time :)
I recently made a login like what you're trying to do. Hopefully you understand this code and it helps:
Dim CMD As OleDbCommand = New OleDbCommand("SELECT * FROM Staff WHERE Login = '" & ID & "'", Con)
Dim user As String
Try
Con.Open()
Dim sdr As OleDbDataReader = CMD.ExecuteReader()
If (sdr.Read() = True) Then
user = sdr("Login")
MessageBox.Show("Login Successful!")
ActiveUser.IsLoggedIn = True
Else
MessageBox.Show("Invalid username or password!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
Con.Close()
End Try
I have a DataGridView where some of the cells only allow values from an AutoCompleteStringCollection. When I enter the cell and begin to type a value, a drop-down window appears with viable options. If I finish typing it out and hit enter or tab, I go to the next cell. However, if I start typing and then select an option from the drop-down menu, it moves one row down in the same column. I’d like it to move to the next cell/next column SAME row after selecting from the drop-down box. Any idea how I go about doing this. Thanks in advance for your help!!
Private Sub getData(ByVal DataCol As AutoCompleteStringCollection)
Dim comm As SqlCommand
Dim adapt As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String = "SELECT DISTINCT ValueOption From HR.dbo.RecruitVal WHERE ColumnName = 'Source'"
Try
If SqlConn.State = ConnectionState.Broken Then SqlConn.Close()
If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
comm = New SqlCommand(sql, SqlConn)
adapt.SelectCommand = comm
adapt.Fill(ds)
adapt.Dispose()
comm.Dispose()
For Each row As DataRow In ds.Tables(0).Rows
DataCol.Add(row(0).ToString())
Next
Catch ex As Exception
MessageBox.Show("Error")
End Try
End Sub
Private Sub RAppSrc(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles RAppGrid.EditingControlShowing
Dim titleText As String = RAppGrid.Columns(RAppGrid.CurrentCell.ColumnIndex).HeaderText
If titleText.Equals("Source") Then
Dim autoText As TextBox = TryCast(e.Control, TextBox)
If autoText IsNot Nothing Then
autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim dataCol As New AutoCompleteStringCollection()
getData(dataCol)
autoText.AutoCompleteCustomSource = dataCol
End If
End If
End Sub
Cell - Validating
If (appCol.Name = "Source") Then
Dim sql As String = " SELECT 1 FROM Hr.dbo.RecruitVal WHERE ColumnName = 'Source'AND ValueOption = #Source "
Dim sql2 As String = "SELECT DISTINCT ValueOption from HR.dbo.RecruitVal WHERE ColumnName = 'Source' "
Dim com As New SqlCommand(sql, SqlConn)
Dim com2 As New SqlCommand(sql2, SqlConn)
Dim reader As SqlDataReader
Dim val As String
Dim val2 As String
com.Parameters.Add("#Source", SqlDbType.VarChar).Value = e.FormattedValue
val = com.ExecuteScalar()
reader = com2.ExecuteReader()
If reader.HasRows Then
While reader.Read()
val2 += reader.GetValue(0) & "," & Space(3)
End While
End If
If String.IsNullOrEmpty(e.FormattedValue) Then
'Do Nothing
ElseIf val = Nothing Then
MessageBox.Show(" Please Enter a valid Source Option" & vbCrLf & vbCrLf & "Valid Options are as Follows:" & vbCrLf & vbCrLf + val2.ToString(), "VALIDATION ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
RAppGrid.EndEdit()
End If
End If
I've tested few scenarios and found out, that the Enter key wouldn't work (all but Enter works). I found this answer on MSDN:
For the enter key, ProcessDataGridViewKey will return true meaning that it has handled the key so you won't get a KeyDown event for it.
If you override ProcessDataGridViewKey and handle the enter key making it return false, you will get the key events you are expecting.
{
Keys key = (e.KeyCode & Keys::KeyCode); //removes control, alt modifiers
if(key == Keys.Enter)
{
//Still do the default processing for enter so it will move down to the next row
Base.ProcessDataGridViewKey(e);
return false; //say we have *not* handled the key
}
else
{
return Base.ProcessDataGridViewKey(e);
}
}
The above code is in C#, obvously.
The move function then may look like this (tested only VB.NET version bellow and only with other keys than Enter):
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If IsNothing(TryCast(e.Control, DataGridViewTextBoxEditingControl)) = False Then
Dim tb As DataGridViewTextBoxEditingControl = e.Control
AddHandler e.Control.KeyDown, AddressOf DataGridView1_Keydown
End If
End Sub
Private Sub DataGridView1_Keydown(sender As Object, e As KeyEventArgs) ' Handles DataGridView1.KeyDown
Dim dgv As DataGridView = DataGridView1
Dim tb As TextBox = CType(sender, TextBox)
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
dgv.EndEdit()
If IsNothing(dgv.CurrentCell) = False Then
Dim cc As DataGridViewCell = dgv.CurrentCell
If cc.ColumnIndex < dgv.Columns.Count - 2 Then ' if there's a cell to the right of the current one
dgv.CurrentCell = dgv.Rows(cc.RowIndex).Cells(cc.ColumnIndex + 1)
ElseIf cc.RowIndex < dgv.Rows.Count - 1 Then ' if there's a row bellow
dgv.CurrentCell = dgv.Rows(cc.RowIndex + 1).Cells(0)
Else
' do nothing, stay where you are
End If
dgv.CurrentCell.Selected = True
End If
End If
End Sub
I need some help with regards on how to identify if the info that i will input on my database is existing or has the same record on my database..Pls i need some help... thank you
here is my code for SAVE BUTTON
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
rs = New ADODB.Recordset
With rs
'check if important item is null '
If txtappln.Text = "" Or txtappfn.Text = "" Or txtappmn.Text = "" Or txtclass.Text = "" Or txtcnum.Text = "" Or txtaddr.Text = "" Or txtbrgy.Text = "" Then
MsgBox("Some object in the Applicant Personal Information or Classification or Ctrl Number is not filled up", MessageBoxIcon.Warning)
.Cancel()
Else
'Save'
.Open("Select * from Applicant", con, 2, 3)
.AddNew()
.Fields("LAST_NAME").Value = txtappln.Text
.Fields("FIRST_NAME").Value = txtappfn.Text
.Fields("MIDDLE_NAME").Value = txtappmn.Text
.Fields("ADDRESS").Value = txtaddr.Text
.Fields("CLASSIFICATION").Value = txtclass.Text
.Fields("CONTROL_NO").Value = txtcnum.Text
.Fields("BARANGAY").Value = txtbrgy.Text
MsgBox("Record has been save !!", vbInformation)
.Update()
.Close()
End If
End With`