|
Public Sub llenaCombo()
Me.cmbCodigoInternoEDC.Items.Clear()
sql = "Select CodigoInterno from [Equipos de Computacion]"
cmd.CommandType = CommandType.Text
cmd.Connection = conn
cmd.CommandText = sql
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While dr.Read()
Me.cmbCodigoInternoEDC.Items.Add(dr.GetValue(0))
End While
End If
dr.Close()
End Sub
Public Sub llenaCombo1()
Me.cmbCodigoInternoVH.Items.Clear()
sql = "Select CodigoInterno from Vehiculos"
cmd.CommandType = CommandType.Text
cmd.Connection = conn
cmd.CommandText = sql
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While dr.Read()
Me.cmbCodigoInternoVH.Items.Add(dr.GetValue(0))
End While
End If
dr.Close()
End Sub
Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click
Dim CodigoInterno As Integer
Dim CodigoInterno1 As Integer
CodigoInterno = Me.cmbCodigoInternoEDC.Text
CodigoInterno1 = Me.cmbCodigoInternoVH.Text
cmd.CommandType = CommandType.Text
cmd.Connection = conn
If sql = "Select * from [Equipos de Computacion]" Then
sql = "delete [Equipos de Computacion] where CodigoInterno= " & CodigoInterno & ""
cmd.CommandText = sql
ElseIf sql = "Select * from Vehiculos" Then
sql = "delete Vehiculos where CodigoInterno= " & CodigoInterno1 & ""
cmd.CommandText = sql
End If
Try
cmd.ExecuteNonQuery()
Me.cmbCodigoInternoEDC.Text = ""
Me.cmbCodigoInternoVH.Text = ""
llenaCombo()
llenaCombo1()
MsgBox("Registro eliminado correctamente")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub>
|
|
|
|
|
The SQL statement is simple:
DELETE FROM tableName
You're already executing SQL statements against the database. This is no different.
|
|
|
|
|
Is not working please help.
|
|
|
|
|
HOW?! Look at what you gave me to work with: "It doesn't work".
What am I supposed to do with that information? I have no idea what code you wrote for this, what you expect the code to do, what the code is actually doing, any error messages, ..., nothing.
Stop typing as little as possible and start explaining EXACTLY what the questions and problems are. Without that, everyone is just guessing at what you want.
|
|
|
|
|
System.InvalidCastException
HResult=0x80004002
Message=La conversión de la cadena "" en el tipo 'Integer' no es válida.
Source=Microsoft.VisualBasic
StackTrace:
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value)
at Activs_Fijos.Reporte.BtnBorrar_Click(Object sender, EventArgs e) in C:\Users\Augusto\source\repos\Activos Fijos\Activos Fijos\Reporte.vb:line 41
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at Activs_Fijos.My.MyApplication.Main(String[] Args) in :line 81
Inner Exception 1:
FormatException: La cadena de entrada no tiene el formato correcto.
|
|
|
|
|
at Activs_Fijos.My.MyApplication.Main(String[] Args) in :line 81
Inner Exception 1:
FormatException: La cadena de entrada no tiene el formato correcto.
The message is telling you what is wrong, and what line number the problem occurs on.
|
|
|
|
|
You haven't told us which line of your original post is line 41, but I'm guessing it's one of these:
CodigoInterno = Me.cmbCodigoInternoEDC.Text
CodigoInterno1 = Me.cmbCodigoInternoVH.Text
The error is telling you that the value in one of those textboxes cannot be converted to an Integer .
Specifically, the textbox is empty. An empty string cannot be converted to an Integer .
Use Integer.TryParse[^] to attempt to convert the user input to an integer. If it fails, report an error to the user.
If Not Integer.TryParse(Me.cmbCodigoInternoEDC.Text, CodigoInterno) Then
Me.cmbCodigoInternoEDC.Focus()
MessageBox.Show("Please enter a valid number")
Return
End If
If Not Integer.TryParse(Me.cmbCodigoInternoVH.Text, CodigoInterno1) Then
Me.cmbCodigoInternoVH.Focus()
MessageBox.Show("Please enter a valid number")
Return
End If
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Im trying to erase Vehiculos and Equipos de computacion with a single button, please help.
|
|
|
|
|
There is no point in repeatedly telling us what you want. Show the code that is failing and explain what happens when you run it. I have already given you a suggestion for your System.InvalidCastException so that is something you can investigate for yourself.
|
|
|
|
|
I changed the sql code for this:
sql = "delete v from Vehiculos v LEft join [Equipos de Computacion] e on v.CodigoInterno = e.CodigoInterno where v.CodigoInterno = " & CodigoInterno & ""<br />
sql += "delete e from [Equipos de Computacion] e Left join Vehiculos e on e.CodigoInterno = v.CodigoInterno where e.CodigoInterno = " & CodigoInterno1 & ""<br />
cmd.CommandText = sql
I want the two tables erased. The queries work for separated i only can erase one table, Im using two comboboxes for each table.
|
|
|
|
|
cmd.CommandText = "DELETE FROM Vehiculos WHERE CodigoInterno = @CodigoInterno; DELETE FROM [Equipos de Computacion] WHERE CodigoInterno = @CodigoInterno1"
cmd.Parameters.AddWithValue("@CodigoInterno", CodigoInterno)
cmd.Parameters.AddWithValue("@CodigoInterno1", CodigoInterno1)
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
Hello,
I have added a DataGridViewComboBoxColumn to a DataGridView and i'm having a little problem.
For testing I am loading one item in the combobox. The item value source is an xml filename without
path or extension; ie. "Foodlion". The xml file has an entry that defines this filename but has a
different case like "FoodLion". After loading the xml file and passing its' value "FoodLion" to the
combobox, I get this context error in DataGridView1.DataError:
Formatting, Display
I'm not performing any formatting on this field since I expect just text.
I get it that the combobox must be performing a FindExact() type search and does not match.
Before I go through the pain staking effort to try an make sure the names match, is there
something I can do change the combobox processing?
Thanks
|
|
|
|
|
Why not load the combobox using either the .ToLower() or .ToUpper() functions? Or if you want it to "look nice" you could always use the TextInfo.ToTitleCase(String) Method (System.Globalization)[^] method.
In general the ComboBox.FindString Method[^] is not case-sensitive so I suspect this has nothing to do with a "FindExact() type search" but you have neither shared code nor the exact wording of the error so it's a little difficult to help further
|
|
|
|
|
Sorry for the confusion.
The error from my post in more clear terms are:
Private Sub DataGridView1_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles MyBase.DataError
{
' DataGridViewDataErrorContexts.Display
' DataGridViewDataErrorContexts.Formatting
Debug.WriteLine(e.Context.ToString())
}
My ComboBox code would not do you any good because it is full of structure data references which would not make sense to you but here is what causes the problem, hopefully more clear.
When I initialize the DataGridView columns, for the combobox object I load the list value which is the filename of the source xml file which happens to be "Foodlion" (note case).
Dim cmb As New DataGridViewComboBoxColumn()
cmb.Items.Add("Foodlion")
I then create a row with the value for the ComboBox which happens to be "FoodLion" (case difference)
because that's the way it was originally created in the xml file.
Me.Rows.Add(dataArray())
This causes the above error whenever the cell is Formatted by the DataGridView.
Making sure the data and the combobox list item are the same case fixes the problem.
So something in the DataGridView formatting doesn't like the case difference. Therefore
that's why I 'assumed' that the ComboBox or underlying code was doing a case sensitive
search; My Bad.
Your Q. Why not load the combobox using either the .ToLower() or .ToUpper() functions?
When the xml file is created the filename is saved in the xml data (in a particular case).
The 'case' of the filename of the file that is stored on disk can change. When I enumerate
the xml files on disk (Directory.GetFiles(path, "*.xml")), I use that filename to load into
the combobox list as above (cmb.Items.Add("Foodlion"). If its' case is not the same as what is stored in the xml file,
I get the DataError.
I just asked the question in case someone may have encountered this type of issue with DataGridViewComboBoxColumn.
I think I have found a work around 'HACK' by saving the filename in the xml file in a particular
format and then formatting the filename from disk the same way.
I hate to HACK code.
Again, sorry for the confusion.
Hope this is clearer.
Thanks 
|
|
|
|
|
Hopefully your hack will work but given that you are apparently doing a
cmb.Items.Add("Foodlion") and
Me.Rows.Add(dataArray()) couldn't you do
cmb.Items.Add(("Foodlion").ToLower) and
Me.Rows.Add(dataArray.Select(c => c.ToLower()).ToArray()) instead?
(Apologies - I'm nowhere near Visual Studio and can't check whether my solution compiles let alone works! Hopefully you get the gist)
|
|
|
|
|
Actually that's basically my hack except that the dataArray comes from my own xml class that loads the xmlfile data into variables (ie an array). The xml class formats the data and my custom DataGridView class loads from the xml class in the way you suggest.
Thanks for you suggestion. 
|
|
|
|
|
So I have a Linq statement, that groups product sales by SKU over a period of about 3 years.
The products go up in price from inflation, so I grab the last price sold for.
But sometimes they will give a product away for free after a sales is made for say $1.00
Last Month - $12.00
This month - Free or $0
I'm trying to figure out how to group the items that have a price above 0
Dim gCustomerItemsAll As List(Of MarginItemCustomerProfit) = sTpAll.Where(Function(w) w.FCustomerNo.Equals(cI.FCustomerNumber)).OrderBy(Function(ob) ob.FItemNo).GroupBy(Function(item) item.FItemNo).Select(Function(cl) New MarginItemCustomerProfit() With {
.FCustomerNumber = cl.First().FCustomerNo,
.FItemNumber = cl.First().FItemNo,
.FShipQty = cl.Sum(Function(qty) qty.FShipQty),
.FCost = cl.Last().FCost,
.FPrice = cl.Last().FPrice,
.FAmount = cl.Sum(Function(amount) amount.FAmount)
}).ToList()
I tried this
.Last(Function(price) price > 0)
but it failed
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
It seems to be quite easy:
Dim gCustomerItemsAll As List(Of MarginItemCustomerProfit) = sTpAll _
.Where(Function(w) w.FCustomerNo.Equals(cI.FCustomerNumber) AndAlso w.Price>0) _
.GroupBy(Function(item) item.FItemNo) _
.Select(Function(cl) New MarginItemCustomerProfit() With _
{ _
.FCustomerNumber = cl.First().FCustomerNo,
.FItemNumber = cl.First().FItemNo,
.FShipQty = cl.Sum(Function(qty) qty.FShipQty),
.FCost = cl.Last().FCost,
.FPrice = cl.Last().FPrice,
.FAmount = cl.Sum(Function(amount) amount.FAmount)
}) _
.ToList()
OrderBy() method call is redundant due to later usage of GroupBy() method.
|
|
|
|
|
I thought about that but didn't give it a try.
I'm glad you didn't say use First() since I forgot to mention that.
I'll try it.
Long time since we have communicated. Hope all is well with you.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
modified 29-Aug-19 14:33pm.
|
|
|
|
|
You're using First and Last within the group, but I don't see any order specified for that operation.
If you just want the last price that's not free, try something like:
.FPrice = cl
.OrderByDescending(Function(i) If(i.FPrice = 0, 0, 1))
.ThenByDescending(Function(i) i.YOUR_DATE_FIELD_HERE)
.First().FPrice
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
First and Last was a tough choice so I chose first for customer and part number and last for cost and price.
Maybe not the best decision and I knew inflation or supply and demand was a factor when I first wrote it.
When I think about it, it probably doesn't matter if the part number is always the same.
But I didn't see the free item after the paid item coming and missed the thought of it occurring.
On a side note mentioned by Maciej on the OrderBy, Guess I should of used the ShipDate for that, for a true first or last. What do you think?
The code runs and free items have been removed from the report now, which is what I wanted and tried to do in code elsewhere. Not sure if I need this line .FShipDate = cl.Last().FShipDate,
If I could make this better, I'd be open to suggestions. The FCost and FPrice bothers me because they fluctuate. Thought about using average but I'm not sure how to implement it.
'Use Linq to Group the Items Together
Dim gCustomersAll As List(Of MarginItemCustomerProfit) = sTpAll.GroupBy(Function(item) item.FCustomerNo).Select(Function(cl) New MarginItemCustomerProfit() With {
.FCustomerNumber = cl.First().FCustomerNo,
.FItemNumber = cl.First().FItemNo,
.FShipQty = cl.Sum(Function(qty) qty.FShipQty),
.FShipDate = cl.Last().FShipDate, // Not sure if I need this line
.FCost = cl.Max(Function(cost) cost.FCost),
.FPrice = cl.OrderByDescending(Function(i) If(i.FPrice = 0, 0, 1)).ThenByDescending(Function(i) i.FShipDate).First().FPrice,
.FAmount = cl.Sum(Function(amount) amount.FAmount)
}).ToList()
If it ain't broke don't fix it
Discover my world at jkirkerx.com
modified 29-Aug-19 14:42pm.
|
|
|
|
|
Imports System.Data.SqlClient
Public Class Equipos_de_Computacion
Dim sql As String = ""
Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
If (Me.txtCodigoInterno.Text = "") Then
MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
Me.txtCodigoInterno.Select()
Else
Dim CodigoInterno As Integer
Dim NumerodeSerie As Integer
Dim NumerodeFactura As Integer
Dim FechadeCompra As Date
Dim Precio As Decimal
Dim Acargode As String = ""
Dim Estado As String = ""
Dim Depreciacion As Decimal
Dim Caracteristicas As String = ""
CodigoInterno = CInt(Me.txtCodigoInterno.Text)
NumerodeSerie = CInt(Me.txtNumerodeSerie.Text)
NumerodeFactura = CInt(Me.txtNumerodeFactura.Text)
FechadeCompra = CDate(Me.DateTimePicker1.Value)
Precio = Me.nudPrecio.Value
Acargode = Me.txtACargode.Text
Estado = Me.txtEstado.Text
Depreciacion = Me.NudDepreciacion.Value
Caracteristicas = Me.txtCaracteristicas.Text
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion)"
sql += "Values('" & CodigoInterno & "','" & NumerodeSerie & "','" & NumerodeFactura & "','" & FechadeCompra & "', '" & Precio & "' ,'" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & Depreciacion & "')"
MsgBox(sql)
cmd.CommandText = sql
Try
cmd.ExecuteNonQuery()
MsgBox("Registro insertado correctamente")
Catch ex As Exception
If ex.ToString.Contains("duplicate") Then
MsgBox("El registro ya existe en la base de datos")
Else
MsgBox(ex.ToString)
End If
End Try
End If
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvEquiposdeComputacion.CellContentClick
End Sub
Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click
Dim DS As New DataSet
Dim DA As New SqlDataAdapter("Select * from [Equipos de Computacion]", conn)
DA.Fill(DS)
dgvEquiposdeComputacion.DataSource = DS.Tables(0)
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
End Sub
Private Sub BtnTotalDepreciacion_Click(sender As Object, e As EventArgs) Handles btnTotalDepreciacion.Click
NudDepreciacion.Value = CDec(FormatNumber(nudPrecio.Value * 0.25, 2))
End Sub
Private Sub TxtPrecio_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub txtPrecio_KeyPress(sender As Object, e As KeyPressEventArgs) Handles nudPrecio.KeyPress
nudPrecio.DecimalPlaces = 2
End Sub
Private Sub txtPrecio_LostFocus(sender As Object, e As EventArgs)
Dim VarMonedaDolares As Double
VarMonedaDolares = nudPrecio.Value
nudPrecio.Value = CDec(FormatCurrency(VarMonedaDolares, 2))
End Sub
End Class
|
|
|
|
|
It means you are somewhere comparing numbers to characters and not including the '' around them or you are trying to put a word into a number field.
You first need to switch your code to using Parameters instead of concatenating your sql because you are susceptible to sql injection attacks. And you can't handle single quotes in your data the way you're doing it, which might actually be causing your issue anyway.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
cmd.CommandText = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion) VALUES (@CodigoInterno, @NumerodeSerie, @NumerodeFactura, @FechadeCompra, @Precio, @Acargode, @Estado, @Caracteristicas, @Depreciacion)"
cmd.Parameters.AddWithValue("@CodigoInterno", CInt(Me.txtCodigoInterno.Text))
cmd.Parameters.AddWithValue("@NumerodeSerie", CInt(Me.txtNumerodeSerie.Text))
cmd.Parameters.AddWithValue("@NumerodeFactura", CInt(Me.txtNumerodeFactura.Text))
cmd.Parameters.AddWithValue("@FechadeCompra", CDate(Me.DateTimePicker1.Value))
cmd.Parameters.AddWithValue("@Precio", Me.nudPrecio.Value)
cmd.Parameters.AddWithValue("@Acargode", Me.txtACargode.Text)
cmd.Parameters.AddWithValue("@Estado", Me.txtEstado.Text)
cmd.Parameters.AddWithValue("@Caracteristicas", Me.txtCaracteristicas.Text)
cmd.Parameters.AddWithValue("@Depreciacion", Me.NudDepreciacion.Value) Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
Once you've fixed that critical security vulnerability in your code, you'll need to check that the values you're trying to insert match the data types of the columns in your table.
You should also avoid using CInt and CDate to convert user input. If the user types in something that can't be converted, you'll get an exception. Instead, use Integer.TryParse[^] / Date.TryParse[^] and display a warning to the user if their input is invalid.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|