VB.NET - System.InvalidCastException (Datagridview) - sql

I get the following error:
System.InvalidCastException: 'Unable to cast object of type 'System.EventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'.'
In this procedure:
Private Sub FillUsersGrid()
Dim sql As String = "SELECT * FROM Users"
Dim dataadapter As New SqlDataAdapter(sql, SQLconn)
Dim Users As New DataSet()
SQLconn.Open()
dataadapter.Fill(Users, "Users_table")
SQLconn.Close()
DgdUsersList.DataSource = Users
DgdUsersList.DataMember = "Users_table"
Me.DgdUsersList.AutoResizeColumns()
End Sub
When I change the following procedure's name:
Private Sub DgdUsersList_SelectionChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DgdUsersList.SelectionChanged
If e.RowIndex >= 0 Then
Row = Me.DgdUsersList.Rows(e.RowIndex)
TxtEmployeesUsername.Text = Row.Cells("Username").Value.ToString
TxtEmployeesPassword.Text = Row.Cells("Password").Value.ToString
CmbEmployeesAccessLevel.Text = Row.Cells("AccessLevel").Value
ChkEmployeesPOSAccess.Checked = Row.Cells("POSAccess").Value
CmbEmployeesPOSPosition.Text = Row.Cells("POSPosition").Value.ToString
End If
DgdUsersList.Rows(CurrentRowIndex).Selected = True
End Sub
From:
Private Sub DgdUsersList_CellClicked(sender As Object, e As DataGridViewCellEventArgs) Handles DgdUsersList.CellClicked
To:
Private Sub DgdUsersList_SelectionChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DgdUsersList.SelectionChanged
The scenario is this; I have two Datagridview controls and I want to make it so that when I click on any cell in DgdEmployeesList, the same row (index) is selected in DgdEmployeesList.
This is because I want to populate a form with a record when a record is clicked, and the employees table in the SQL database is linked to the users one in the same database via a primary key (ID - When an employee profile is created, a user profile is created with the same ID using the same form)
Is there any fix for this (I understand it may be easier to code this just by using the datagridview control itself, but I am unaware of a way to make two tables display inside the control and how to separate them upon saving, along with editing records and deleting them)
Any help is greatly appreciated!
James

Related

OnSelectedIndexChanged no working in aspx Page

i have this dropdownlist in my page
<asp:DropDownList ID="ddlselectTaxas" runat="server" AutoPostBack="True" CssClass="form-control" OnSelectedIndexChanged="ddlselectTaxas_SelectedIndexChanged"
EnableViewState="True" ViewStateMode="Enabled"></asp:DropDownList>
and this is the function in the vb file
Public Sub ddlselectTaxas_SelectedIndexChanged(sender As Object, e As EventArgs)
taxas.TryGetValue(ddlselectTaxas.SelectedItem.Text, valorTxt.Text)
valorTxt.Text = valorTxt.Text.Substring(0, valorTxt.Text.Length - 2)
End Sub
I want to change the value of a textbox (valorTxt) when I select a diferent value in the dropdownlist, but the function is not firing. I dont know why, i have zero experience with VB and asp pages. I apreciate your help. thanks in advance.
EDIT
here is the full code of the page
Public Class Emitir
Inherits System.Web.UI.Page
Public taxas As New Dictionary(Of String, String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
CarregaValores()
valorTxt.ReadOnly = True
End If
End Sub
Private Sub CarregaValores()
Dim dt As DataTable
Dim objAcesso As New AcessoBD
Dim consulta As String = "SELECT TE.COD_TAXA, TE.DESC_TAXA, TV.VL_TAXA FROM TAXAS_EXPEDIENTE TE JOIN TAXAS_EXPEDIENTE_VALOR TV ON TE.COD_TAXA = TV.COD_TAXA"
dt = objAcesso.DataTable(consulta, CommandType.Text)
For Each linha As DataRow In dt.Rows
taxas.Add(linha.ItemArray(1), linha.ItemArray(2))
Next
valorTxt.Text = dt.Rows.Item(0).ItemArray(2)
valorTxt.Text = valorTxt.Text.Substring(0, valorTxt.Text.Length - 2)
ddlselectTaxas.DataTextField = "DESC_TAXA"
ddlselectTaxas.DataValueField = "COD_TAXA"
ddlselectTaxas.DataSource = dt
ddlselectTaxas.DataBind()
End Sub
Protected Sub ddlselectTaxas_SelectedIndexChanged(sender As Object, e As EventArgs)
taxas.TryGetValue(ddlselectTaxas.SelectedItem.Text, valorTxt.Text)
valorTxt.Text = valorTxt.Text.Substring(0, valorTxt.Text.Length - 2)
End Sub
End Class
You don't show your code to load up the drop list.
Remember, your page load code fires EVERY time on post back.
So, if in code on page load, you load up the drop list? You need to do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
LoadCal()
End If
End Sub
Sub LoadData()
Dim cmdSQL As New SqlCommand(
"SELECT ID,(FirstName + ' ' + LastName) as EmpName
FROM Employee ORDER BY FirstName")
lstEmployee.DataSource = MyRstP(cmdSQL)
lstEmployee.DataBind()
End Sub
Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Now, in above, I was using a listbox, but they work the same as a drop down list (combo box).
but, if you do NOT place the loading up of data inside of the If Not IsPostBack?
Then what happens is you select a drop down, and say click on a button (or in your case autopostback = true, then the page load FIRES FIRST and THEN your code runs!!!
and, if your code re-loads the drop list? Then your selection is lost!!!
So, for just about ANY page you create, ALWAYS, but always use the is postback code stub in on-load - and thus your loading of controls data ONLY occurs one time. Since if you re-load every time, then you lose your changes.
Well, I am not sure of what was happening, but I remade my page and it is working now. something was blocking the event. Thanks for your help.

How to use DataGridView and a button to delete a SQL entry in my DataGridView

So I've got my SQL connection setup and working and it pulls and binds the data to the datagridview. I have an update button that pushes the edited data back to the SQL server.
Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
'Delete Current Cell Data
Dim deleteCmd As String = "Delete FROM Contacts WHERE au_id = #Id;"
Dim myCommand As SqlCommand = New SqlCommand(deleteCmd)
myCommand.Parameters.Add(New SqlParameter("#Id", SqlDbType.VarChar, 11))
'Start the SqlCommand "#Id" parameter to the ID of the row that was clicked.
myCommand.Parameters("#Id").Value = DataGridView1.SelectedCells
Now I am currently working on getting a delete button to function. Basically I need it to Delete the row of data that is currently selected.
Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
If DataGridView1.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
This is what I came up with! I was going about it all wrong attempting to do it via SQL queries. Just needed to do it locally and then use my update button to finish the changes. Which will probably be safer given that end users are end users.

get ID from datagridview and show the data to another form in textboxes

Im kind of new in vb.net. I have a datagridview that shows the Delivery Number, Date and supplier. Now, I want the Admin to view the details of every delivery to another form. I just want to know how will I get the id of the selected row and then will be able to display the equivalent data of that selected ID. Thanks.
Here's my code for the Deliveries Form.
Private Sub dgvDeliveryReport_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvDeliveryReport.CellContentDoubleClick
If e.RowIndex < 0 Then Exit Sub
Dim id As Int32 = dgvDeliveryReport.CurrentRow.Cells(0).Value
Dim viewDelivery As New frmDeliveryFormReport
frmDeliveryFormReport.Show()
End Sub
In your frmDeliveryFormReport class add a new field to store current row:
private _currentDeliveryReportRow as DataGridViewRow
Look for the constructor:
Public Sub New frmDeliveryFormReport()
...
End Sub
(If you cannot find it just proceed with the next step).
Change/Add the constructor so it takes the DataGridViewRow parameter and store the given row:
Public Sub New frmDeliveryFormReport(deliveryReportRow as DataGridViewRow)
_currentDeliveryReportRow = deliveryReportRow
End Sub
Adapt your existing dgvDeliveryReport_CellContentDoubleClick to call the new constructor:
Private Sub dgvDeliveryReport_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvDeliveryReport.CellContentDoubleClick
If e.RowIndex < 0 Then Exit Sub
Dim viewDelivery As New frmDeliveryFormReport(dgvDeliveryReport.CurrentRow)
frmDeliveryFormReport.Show()
End Sub
You can then access all columns of the DeliveryReportRow in the frmDeliveryFormReport via
_currentDeliveryReportRow.Cells(<CellIndex>)
Additional information about this topic:
Passing variables between windows forms in VS 2010
VB.Net Passing values to another form
http://www.dreamincode.net/forums/topic/332553-passing-data-between-forms/
Try.
Dim newFrmName as new yourForm
For each row as DataGridViewRow in SampleGrid
if row.selected = true then
Dim whatValueYouWant as string = row.cells("ID").value.toString()
if newFrmName.NameOfTextBoxInForm.Text <> vbEmpty Then
'NameOfTextBoxInForm is textbox that existing in yourform
newFrmName.NameOfTextBoxInForm.text = ", " & whatValueYouWant
Else
newFrmName.NameOfTextBoxInForm.text = whatValueYouWant
End If
End IF
Next
newFrmName.Show()

how to update, insert records through datagridview to sql using data adapter or other method in vb.net

hello best programmers in the world i need your expert advise and assistance with regards to my project.
I am trying to insert and update my table through datagridview by clicking a command button,
i have my datagridview properties set to editmode : editprogrammatically,
here's the code, of where i pulled up my datagridview content:
Public Sub loaddgvfrm3()
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = sqlstr
cmdconn.Open()
cmd.Connection = cmdconn
cmd.CommandText = "select period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO from tobee.EBD_BILLHISTORY where CLAIM_NO like '" + txtClaimno.Text + "'"
Dim dt As New DataTable
da = New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
Me.DataGridView2.DataSource = dt
cmdconn.Close()
End Sub
now i have my command buttons here
here's the add button: (im prefering to add a row within the selected table)
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
End Sub
here's the Edit button:
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
''Form1.ShowDialog()
'DataGridView2.AllowUserToAddRows = True
''DataGridView2.BeginEdit(True)
'btnSave.Enabled = True
End Sub
and here's the save button that should save all changes that i have done,
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connstr As String = "server=midtelephone\sqlexpress; database=testdb; user= sa; password=sa;"
End Sub
i left command button contents empty because i need to create a new method of inserting, updating the row. because the one that i have earlier was a fail, although it inserts the data in the sql, but not in its appropriate row, take a look at here: Data inserted from datagridview not updated in SQL Server , instead it creates another row which is not connected with '" + txtClaimno.Text + "'" (stated from above) so what happens is that it stacks a new row with no connected owner from another table(claim_no < this claim_no is connected from another table as a fk in the database but a primary key in (billhistory table))
can you pls help me get rid of this problem as i am having a hard time moving to the next phase of our project? im just a high school student, so pls bear with me :) i'll appreciate if u give comments / answers regarding my question :) thanks in adv.
my mentor advised me to use data adapter accept changes stuff, but i don't know how to implement such stuffs. pls help me thank you :)
Use Event to get data from gridview on cellConttent Click and these values to a query or Stored procedure.
private void grdCampaignStats_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//I want to get value of SomeColumn of grid view having datatype String
string SomeVariabel = grd["CoulmnNameinGRID", e.RowIndex].Value.ToString();
// Make it according to Vb it is C# code
}

Populate an ado.net dataset with only changes from the data source

This is so simple, I must be stupid!
I have a simple access database that a log record gets written to a few times an hour.
I'm trying to make a DataGridView that shows that data as it arrives.
My "Solution" is simple;
when a user clicks the view -> read from the database (fill the datatable) -> update the view.
Not what I dreamed of, but functional, if totally sub-optimal.
However, my "solution" is a dud, using fill draws every single record from the database, even if there are already 599 on screen.
Really, I just want fill the datatable once, and add new records as they arrive (or on click if needs be).
Bonus point if you can also explain another way (that isn't called so often) to hide the ID column, and change the header of column 1 (named DateTimeStamp) to TimeStamp.
Public Class FormMain
Shared dataAdapter As OleDbDataAdapter
Shared logTable As New DataTable("log")
Shared commandBuilder As OleDbCommandBuilder
Shared queryString As String = "SELECT * FROM log"
Shared bindingSource As New BindingSource
Private Sub FormServerBridge_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
ConfigureDataSet()
ConfigureBindingSource()
ConfigureDataView()
Catch ex As Exception
' FIXME: Helpful for debugging purposes but awful for the end-user.
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ConfigureDataSet()
dataAdapter = New OleDbDataAdapter(queryString, _Config.ConnectionString)
commandBuilder = New OleDbCommandBuilder(dataAdapter)
commandBuilder.GetUpdateCommand()
dataAdapter.Fill(logTable)
With logTable
.Locale = System.Globalization.CultureInfo.InvariantCulture
.PrimaryKey = New DataColumn() {logTable.Columns("ID")}
End With
End Sub
Private Sub ConfigureBindingSource()
With bindingSource
.DataSource = logTable
End With
End Sub
Private Sub ConfigureDataView()
With DataGridView
.DataSource = bindingSource
End With
End Sub
Private Sub DataGridView_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView.Click
UpdateUI()
End Sub
Sub UpdateUI()
dataAdapter.Fill(logTable)
End Sub
Private Sub DataGridView_DataBindingComplete(ByVal sender As Object, ByVal e As DataGridViewBindingCompleteEventArgs) Handles DataGridView.DataBindingComplete
' FIXME: This code gets run as many times as there are rows after dataAdapter.Fill!
With DataGridView
.Columns("ID").Visible = False
.Columns(1).HeaderText = "Timestamp"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
.Columns(3).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
End Class
p.s. Links to websites and books will be appreciated, even the right MSDN page (if you know where it is, I admit I find it uncomfortable to peruse, I regularly get lost).
Assuming your IDs are sequential, the way I would approach this is:
1) Record the last id that you retrieved
2) When the user presses view, only get records whose IDs are greater than the last one record
3) Retrieve the records into a new datatable and then merge that with your existing data set.
Here is how I would make the changes (only changed info included):
Public Class FormMain
Shared logTable As DataTable
Shared bindingSource As New BindingSource
Private m_wLastID As Integer
Private Sub FormServerBridge_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
ConfigureDataSet()
ConfigureBindingSource()
ConfigureDataView()
Catch ex As Exception
' FIXME: Helpful for debugging purposes but awful for the end-user.
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ConfigureDataSet()
Dim queryString As String
queryString = "SELECT * FROM log WHERE ID > " & m_wLastID.ToString & " ORDER BY ID"
Using dataAdapter As New OleDbDataAdapter(queryString, _Config.ConnectionString)
Using commandBuilder As New OleDbCommandBuilder(dataAdapter)
Dim oDataTable As New DataTable("log")
commandBuilder.GetUpdateCommand()
dataAdapter.Fill(oDataTable)
With oDataTable
.Locale = System.Globalization.CultureInfo.InvariantCulture
.PrimaryKey = New DataColumn() {.Columns("ID")}
End With
' Record the last id
If oDataTable.Rows.Count <> 0 Then
m_wLastID = CInt(oDataTable.Rows(oDataTable.Rows.Count - 1)("ID"))
End If
If logTable Is Nothing Then
logTable = oDataTable
Else
logTable.Merge(oDataTable, True)
logTable.AcceptChanges()
End If
End Using
End Using
End Sub
Sub UpdateUI()
ConfigureDataSet()
End Sub
' Rest of the form code here