need help on this
TRANSCRIPT
need help on this; I want to have the textbox4 to have the sum of columns based on their
employee Id.
I have this code but kept getting error.
strsql = "SELECT emp_id, COUNT(acdcalls) FROM CMS WHERE emp_id= '" &
TextBox1.Text & "'"
oledbcon.Open()
Dim cmd As New OleDbCommand(strsql, oledbcon)
Dim reader As OleDbDataReader = cmd.ExecuteReader
reader.Read()
TextBox4.Text = reader("acdcalls")
reader.Close()
oledbcon.Close()
please help I'm a newbie here.:sweat:
coolzero
Newbie Poster
5 postssince Apr 2008
0 6 Years Ago
strsql = "SELECT sum(acdcalls) as acdcalls FROM CMS where emp_id= '" &
TextBox1.Text & "'"
oledbcon.Open()
Dim cmd As New OleDbCommand(strsql, oledbcon)
Dim reader As OleDbDataReader = cmd.ExecuteReader
reader.Read()
TextBox4.Text = reader("acdcalls")
reader.Close()
oledbcon.Close()
Question Self-Answered as of 6 Years Ago
Jx_Man
Senior Poster
3,543 postssince Nov 2007
•Featured
1 6 Years Ago
COUNT function to count how much record in current column.
SUM function to added all value in current column.
AVG function to get average of all value in current column.
etc...
Well Great to solved your thread by your self.
Happy coding friend :)
Naveen2961
Newbie Poster
6 postssince Aug 2011
0 2 Years Ago
I am trying to get the Sum values of a Column and want to check if entered value in
Textbox is valid.
Here is my code below
mystr = ("Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source=K:\Amrut Diary\Amrut_Diary\ADDB.mdb")
con = New OleDb.OleDbConnection(mystr)
con.Open()
strsql = "SELECT SUM(Available_Stock) As Avstk FROM STOCKDB Where
Material_Name= '" & TMtNm.Text & "'"
Dim cmd As New OleDbCommand(strsql, con)
Dim reader As OleDbDataReader = cmd.ExecuteReader
cmd.ExecuteReader()
If TQty.Text > reader("Avstk") Then
MsgBox("Quantity Overflow")
TQty.Text = ""
TQty.Focus()
End If
When I execute, I am Getting "No value given for one or more required parameters." Error
How to use SUM () in vb.net
i have do 1 program to record employee working hours, so at the end , i have to use my program to sum all the employee working in specific job no.....
i try some code in vb.net but prompt out error (An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in system.data.dll)
strSQL = "SELECT sum(HoursInMin) FROM ProjectTable WHERE DepartmentName = 'Design' AND ProjectNo = " & FindTextBox.Text & "" oledbcon.Open() Dim cmd As New OleDbCommand(strSQL, oledbcon) cmd.ExecuteScalar()----------error on this line oledbcon.Close()
anyone can help me onl this.....thanx alot
07-07-2005 at 02:29 AM |
GoranLevel: Moderator
Registered: 16-05-2002Posts: 1652
Re: How to use SUM () in vb.net
Of what type is field ProjectNo? Is it numeric? Try explicitly converting textbox value to numeric type that is the same as ProjectNo.
Also, declare a variable that will hold the value that is returned from ExecuteScalar function.
____________________________If you find the answer helpful, please mark this topic as solved.
10-07-2005 at 05:29 PM |
MichaelEeLevel: Protégé
Registered: 07-07-2005Posts: 4
Re: How to use SUM () in vb.net
my ProjectNO in ms access i set to text.....i solve the prompt out error already, but in the textbox1.text there i can't get the SUM(TotalInMin) from the command , whether my coding is correct??
11-07-2005 at 12:45 AM |
GoranLevel: Moderator
Registered: 16-05-2002Posts: 1652
Re: How to use SUM () in vb.net
If it is a text type field, then you need to put value between single quotes, as you have probably done, since you say you have solved the error.
As for displaying the return value, you need to declare a variable that will receive the return value, as I said. Something like
Dim x as double
x=cmd.executescalar() textbox1.text=x.tostring
____________________________If you find the answer helpful, please mark this topic as solved.
11-07-2005 at 03:05 PM |
fabulousLevel: VB Guru
Registered: 03-08-2002Posts: 435
Re: How to use SUM () in vb.net
Another way if you are going to be getting more than one aggregate value from your query (perhaps the totals of 3 fields, and the average of another), you can use the SQL query itself to create a column that you can then read from like so:
'put such a query in the command...Dim sql As String = "SELECT sum(HoursInMin) AS TotalTime, AS ..." 'the rest of the items come here'... later in your code...Dim dr As OleDbDataReader = cmd.ExecuteReader() 'close connection here'Get your total hours from the data readerdr.Read()Dim time As Double = dr("TotalTime")'the rest of your code...
Just as a note, I am in an internet cafe and I am air coding, (coding from the top of my head), so you will have to verify a couple of things if you use this code (such as the CloseConnection behaviour of the ExecuteReader() method, I cannot remember the name of the enumeration so you will have to check that part out.)
Happy coding.
____________________________
My boss is a Jewish Carpenter (Jesus Christ)
Brain Bench Certified VB.NET Developer
11-07-2005 at 04:58 PM |
MichaelEeLevel: Protégé
Registered: 07-07-2005Posts: 4
Re: How to use SUM () in vb.net
actually i only need to sum up 1 field, i m using the method that Goran show here, but i got the other error prompt out:"An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in system.data.dll"
here is the code:
Private Sub DesignTotalHours_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DesignTotalHours.Click
strSQL = "SELECT sum(HoursInMin) from ProjectTable where DepartmentName = 'Design' and ProjectNo = " & TotalHr.Text & " "
If oledbcon.State = ConnectionState.Closed Then oledbcon.ConnectionString = con oledbcon.Open() End If
Dim cmd As New OleDbCommand(strSQL, oledbcon)
da = New OleDbDataAdapter(cmd) da.InsertCommand = cmd
Dim selectedProjNo As String = TotalHr.Text
If Not selectedProjNo Is Nothing And selectedProjNo <> "" Then da.InsertCommand.Parameters.Add(" & TotalHr.text & ", OleDbType.VarChar, 50, "ProjectNo") da.InsertCommand.Parameters(0).Value = selectedProjNo Else
MsgBox("Please Enter Project No", MsgBoxStyle.Critical, "Global Mould Time Sheets") Exit Sub End If
Dim JobHoursInMin As Integer
JobHoursInMin = da.InsertCommand.ExecuteScalar
Dim hr As Integer = Math.Floor(JobHoursInMin / 60) Dim min As Integer = JobHoursInMin Mod 60 Dim MinInTwoDigits As String
If min.ToString.Length = 1 Then MinInTwoDigits = "0" + min.ToString Else MinInTwoDigits = min.ToString
End If
TextBox1.Clear()
Dim strTotalHr As String = hr.ToString + ":" + MinInTwoDigits
TextBox1.Text = strTotalHr
DesignTotalHours.Enabled = False
If oledbcon.State = ConnectionState.Open Then oledbcon.Close() da.Dispose() oledbcon.Dispose() End If End Sub
Izzit any wrong on my coding, please give me some advise....thanx a lot.....
Dim cmd3 As New OleDbCommand("Select sum(Quantity) from assetcategory where ID ='A013' and Asset_Name='CPU'", con) Dim dr1 As OleDbDataReader dr1 = cmd3.ExecuteReader While dr1.Read Label4.text=dr1.item(0).Tostring End While
Here is the code I have thus far:
Public Class frmTotal Dim dt As New DataTable() Dim rowindex As Integer = 0 Dim connstr As String = "provider=microsoft.jet.oledb.4.0;" & "data source=valleyfair.mdb" Dim sqlstr As String = "select * from employee"
Private Sub btnTotal_Click(sender As System.Object, e As System.EventArgs) Handles btnTotal.Click
End Sub
Private Sub frmTotal_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load dt.Clear() Dim dataAdapter As New OleDb.OleDbDataAdapter(sqlstr, connstr) dataAdapter.Fill(dt) dataAdapter.Dispose() End SubEnd Class
1. dbCommand = New OleDbCommand2. dbCommand.Connection = New OleDbConnection(DataBase)3. dbCommand.Connection.Open()4. dbCommand.CommandText = "SELECT SUM(TransactionAmount) FROM Transactions
WHERE Budget='" & cmbBudget.Text & "'"5.6. Reader = dbCommand.ExecuteReader7.8. While Reader.Read9. TextBox1.Text = Reader.GetValue(0)10. End While
Respuesta: ¿Como implementar UPDATE() y SUM() ?
Hola easolano5
El update lo puedes hacer de la siguiente manera:
Código vb:
Ver original
1. UPDATE " tabla " SET "campo_a_modificar " = "nuevo_valor " WHERE " & condicion
El sum de la siguiente manera para evitar errores:
Código vb:
Ver original
1. SELECT ISNULL(SUM(" columna"),0) FROM " tabla " WHERE " & condicion
Ahora bien nose si donde dices que no sabes como hacerlo en vb te refieres a la ejecución de estos comandos o si tu problema esta en la creación de dichos comandos (querys).
De ser la primera opción te agrego esto.
Para el Update:
Código vb:
Ver original
1. Public Sub EjecutarQuery(ByVal sql As String, ByVal objConn As SqlConnection)
2. 3. Dim cmd As System.Data.SqlClient.SqlCommand4. cmd = New System.Data.SqlClient.SqlCommand()5. cmd.Connection = objConn6. cmd.CommandText = sql7. cmd.ExecuteNonQuery()8. 9. End Sub
Para el Sum:
Código vb:
Ver original
1. Public Function EjecutarEscalar(ByVal sql As String, ByVal objConn As SqlConnection)
2. 3. Dim total As Double4. 5. Dim cmd As System.Data.SqlClient.SqlCommand6. cmd = New System.Data.SqlClient.SqlCommand()7. cmd.Connection = objConn8. cmd.CommandText = sql9. total = cmd.ExecuteScalar10. 11. Return total12. 13. End Function
Pueden existir distintas formas pero yo utilizo las mencionadas anteriormente.
0
Inicie sesión para votar
Hola Apresiados Expertos...
Mi problema es que necesito algun procedimiento que me permita sumar valores
contenidos en una tabla de SQL SERVER y presentar el resultado en una caja de texto
en VB.NET 2010.
He intentado con una idea que me proporcionaron pero no resulta. Aqui el codigo:
Sub SUMA_RECARGO_MENSUAL()
Dim I As Integer
Dim CONSULTA As String = "SELECT SUM(RECARGO) FROM TbRecargo"
I = Val(CONSULTA)
CBO_RECARGO.Text = I
end sub
Espero con asias su ayuda... Gracias de antemano.
0
Inicie sesión para votar
hola
y si usas
Using cn As New SqlConnection(ConnectionString)
cn.Open()
Dim query As String = "SELECT SUM(RECARGO) FROM TbRecargo"
Dim cmd As New SqlClient.SqlCommand(query, cn)
CBO_RECARGO.Text = CStr(cmd.ExecuteScalar())
End Using
o sea deebs establecer al conexion a la db para poder eejcutar la query que defines
sing cn As New SqlConnection(ConnectionString) cn.Open()
Dim query As String = "SELECT SUM(RECARGO) FROM TbRecargo" Dim cmd As New SqlClient.SqlCommand(query, cn) CBO_RECARGO.Text = CStr(cmd.ExecuteScalar()) End Using
Bueno haber si algun experto me hecha una mano como dicen por ahi. quisiera hacer este grafico pero ni idea de como hacerlo con el msChart control.
En el campo principal en este caso sera "Motores" y este es el unico que cambiara lo demas solo debe mostrar las cantidades. La conexion y todo lo demas lo tengo solo me falta el report.
Lo mas importante de todo es que los valores se muestren en la misma barrita para leerlos facilmente, el report es bastante simple pero no encuentro nada.
Aqui otra imagen donde se muestran las cantidades en las misma barras.
NOTA:Lo curioso es que he intentado hacerlo con office2007 y hace lo que quiero menos mostrar la cantidad en las barras como en la imagen anterior.
« última modificación: Marzo 31, 2012, 01:16:51 pm por lucius »
En línea
Virgil Tracy Bytes
Mensajes: 42
Reputación: +27/-1
o
Re:Crear grafico con microsoft chart« Respuesta #1 en: Marzo 31, 2012, 11:05:07 pm »
pone un mschart y el siguiente codigo en un form
Código: Visual Basic
1. Option Explicit
2.
3. Private Sub Form_Load()
4.
5. DrawChart
6.
7. End Sub
8.
9.
10.
11. Private Sub DrawChart()
12.
13. ReDim g(1 To 4, 1 To 2)
14.
15. g(1, 1) = "15/01/2011"
16. g(1, 2) = 60
17.
18. g(2, 1) = "25/05/2011"
19. g(2, 2) = 90
20.
21. g(3, 1) = "14/06/2011"
22. g(3, 2) = 50
23.
24. g(4, 1) = "18/08/2011"
25. g(4, 2) = 120
26.
27. With MSChart1
28.
29. .AllowSelections = False
30. .AllowSeriesSelection =
False
31.
32. With .Title
33. .Text = "Ejemplo
MsChart"
34.
35. With .VtFont
36. .Name =
"Microsoft Sans Serif"
37. .Size = 16
38. .VtColor.Set 0,
128, 0
39. .Style =
VtFontStyleBold
40. End With
41.
42. End With
43.
44. .ChartData = g
45.
46. .chartType =
VtChChartType2dBar
47. .SeriesType =
VtChSeriesType2dBar
48. .ShowLegend = False
49. .Plot.DataSeriesInRow =
False
50. .ColumnLabel = ""
51.
52.
With .Plot.Axis(VtChAxisIdX)
53.
54. .Pen.VtColor.Set 192,
192, 192
55.
56.
With .AxisGrid.MajorPen
57. .VtColor.Set 192,
192, 192
58. End With
59.
60. End With
61.
62.
With .Plot.Axis(VtChAxisIdY)
63.
64. .Pen.VtColor.Set 192,
192, 192
65.
66.
With .AxisGrid.MajorPen
67. .VtColor.Set 192,
192, 192
68. End With
69.
70. End With
71.
72.
.Plot.Axis(VtChAxisIdY2).AxisScale.
Hide = True
73.
74.
With .Plot.Axis(VtChAxisIdY).AxisTi
tle
75.
76. .TextLayout.Orientatio
n = VtOrientationHorizontal
77. .Text = "Motores"
78.
79. With .VtFont
80. .Name =
"Microsoft Sans Serif"
81. .Size = 10
82. .VtColor.Set 255,
0, 0
83. .Style =
VtFontStyleBold
84. End With
85.
86. End With
87.
88.
With .Plot.SeriesCollection(1).Data
Points(-1)
89.
90. With .Brush
91. .Style =
VtBrushStyleSolid
92. .FillColor.Set
252, 159, 0
93. End With
94.
95. With .EdgePen
96. .Style =
VtBrushStyleSolid
97. .VtColor.Set 130,
73, 0
98. End With
99.
100. End With
101.
102.
With .Plot.SeriesCollection(1).Data
Points(-1).DataPointLabel
103. .LocationType =
VtChLabelLocationTypeAbovePoint
104. .Component =
VtChLabelComponentValue
105. .PercentFormat = ""
106.
107. With .VtFont
108. .Name =
"Microsoft Sans Serif"
109. .Size = 8
110. End With
111.
112. End With
113.
114. End With
115.
116. End Sub
117.
118.
En línea
lucius Megabyte
Mensajes: 207
Reputación: +5/-5
o
Re:Crear grafico con microsoft chart« Respuesta #2 en: Abril 01, 2012, 12:59:52 am »
Virgil eres lo maximo actualmente lo habia logrado creando un grafico en Access2007 y
exportandolo a Excel2007(Aqui utilizo las tablas dinamicas), jeje hoy tuve que aprender a utilizar
los graficos, toda una aventura y dolor de cabeza.
El ejemplo que colocas se ve bien, los ejemplos que encontre me sacaban chispa, bueno ya que
la idea era hacerlo en vb6 procedere con tu ejemplo, muchas gracias.
Espero no hacerme problemas ya que los registros los tengo cargados en un recordset intentare
modificarlo supongo que utilizare un for, saludos
rs("id")
rs("Fecha")
rs("Motores")
En línea
YAcosta Exabyte
Mensajes: 2027
Reputación: +106/-32
Daddy de Qüentas
o
o
Re:Crear grafico con microsoft chart« Respuesta #3 en: Abril 01, 2012, 02:45:21 am »
Quiza te pueda interesar el grafico que uso y que en este hilo se comenta:
http://leandroascierto.com/foro/index.php?topic=890.msg4479#msg4479
Saludos
En línea
Me encuentras en YAcosta.com
cristian_19a Kilobyte
Mensajes: 74
Reputación: +25/-3
o
Re:Crear grafico con microsoft chart« Respuesta #4 en: Abril 01, 2012, 06:21:53 am »
hola muchachos bueno yo usaba en vb 6.0 este control
es un control OCX que controla gráficos muy dinamicos en flash con xml
lo pueden descargar aqui
http://www.fusioncharts.com/extensions/visual-basic-6/
en las cual les baja con ejemplos del control, lo pueden usar en NET en PHP en VB 6 en lo que
desean
tambien existe el codigo fuente libre de esto que son los FLA de donde pueden manejara tu
antojo
http://www.4shared.com/rar/KQX3Q9Qz/FusionCharts_Enterprise_v3.htm
el password para el archivo es pepe
úsenlo
gracias
En línea
YAcosta Exabyte
Mensajes: 2027
Reputación: +106/-32
Daddy de Qüentas
o
o
Re:Crear grafico con microsoft chart« Respuesta #5 en: Abril 01, 2012, 04:16:36 pm »
juassss, excelente cristian, me interesa mucho. Gracias
En línea
Me encuentras en YAcosta.com
ssccaann43 Terabyte
Mensajes: 889
Reputación: +87/-58
o
o
Re:Crear grafico con microsoft chart« Respuesta #6 en: Abril 02, 2012, 11:34:31 am »
En el codigo fuente que envias no encuentro nada para VB6... Y en el primer link descarga es un
trial... =(
Me habia emocionado...
En línea
Miguel Núñez.
cristian_19a Kilobyte
Mensajes: 74
Reputación: +25/-3
o
Re:Crear grafico con microsoft chart« Respuesta #7 en: Abril 02, 2012, 12:44:05 pm »
disculpen yo pensé que captaban lo que iban hacer, como les dije antes es un control OCX
que utiliza flash para mostrar los gráficos y lo que esta licenciado es los archivos FLASH que son
de extension SWF
y les mencione que hay una versión libre donde con código fuente que son los FLA que se
encuentran en el segundo link de 4shared en la cual pueden agarrar su editor FLA y editarlo a su
antojo.
bueno aquí les paso los mismos ejemplos que bajan en el demo ya con los SWF de codigo fuente
libre
http://www.4shared.com/rar/ZIG21aP5/FUSCH.html
la contraseña para acceder es 123456
chekeenlo lo dinámico que son estos gráficos, ya que en estos se reflejan la importancia para la
toma de desiciones
Gracias« última modificación: Abril 02, 2012, 07:52:04 pm por cristian_19a »
En línea
ssccaann43 Terabyte
Mensajes: 889
Reputación: +87/-58
o
o
Re:Crear grafico con microsoft chart« Respuesta #8 en: Abril 02, 2012, 04:24:35 pm »
Es decir que podemos usar estos así gratuitos sin problemas?
En línea
Miguel Núñez.
cristian_19a
Kilobyte
Mensajes: 74
Reputación: +25/-3
o
Re:Crear grafico con microsoft chart« Respuesta #9 en: Abril 02, 2012, 08:02:10 pm »
Citar
Es decir que podemos usar estos así gratuitos sin problemas?
es decir?
eso no fue tu duda anteriormente
bueno claro yo lo tengo funcionando perfectamente y adaptado a mis necesidades
y si ah ustedes les surge un problema no duden en comentarlo
Gracias
En línea
Virgil Tracy Bytes
Mensajes: 42
Reputación: +27/-1
o
Re:Crear grafico con microsoft chart« Respuesta #10 en: Abril 03, 2012, 12:49:03 am »
Y probaron RMChart 4.12 es gratuito y tiene incluido un diseñador de graficos ?
http://www.4shared.com/file/m8LFFLbe/setup.html
En línea
cristian_19a Kilobyte
Mensajes: 74
Reputación: +25/-3
o
Re:Crear grafico con microsoft chart« Respuesta #11 en: Abril 03, 2012, 06:34:58 am »
muy bien!!!, ahora hay mas opciones a eligir
Gracias
En línea
seba123neo Terabyte
Mensajes: 744
Reputación: +83/-5
o
Re:Crear grafico con microsoft chart« Respuesta #12 en: Abril 03, 2012, 11:48:33 am »
como casi siempre estos controles de terceros, no son gratis, te dan un trial y dessues a
comprar, si te lo bajas de algun lado pirateado para hacerlo en tu casa esta bien, nadie te va a
decir nada, pero para una empresa de software lo tenes que comprar no te queda otra.
En línea
Quien nunca ha cometido un error nunca ha probado algo nuevo - Albert Einstein
cristian_19a Kilobyte
Mensajes: 74
Reputación: +25/-3
o
Re:Crear grafico con microsoft chart« Respuesta #13 en: Abril 03, 2012, 04:31:22 pm »
como les comente antes los que estan licenciados son los SWF y existe un codigo libre
En línea
lucius Megabyte
Mensajes: 207
Reputación: +5/-5
o
Re:Crear grafico con microsoft chart« Respuesta #14 en: Abril 05, 2012, 03:11:37 am »
cristian_19a no encuentro los archivos con extension .fla dentro de la carpeta FUSCH solo
los .SWF y .xml entiendo que los datos son enviados a los archivos .SWF los cuales generan los
graficos pero como estos estan licenciados ahi el problema. Esos mismos .swf los que mencionas
que pueden editarse? bueno solo es curiosidad y para que quede claro a futuros usuarios.
En línea
IMPRIMIR
Páginas: [1] 2
« anterior próximo »
Visual Basic Foro »
Programación »
Visual Basic 6 (Moderadores: coco, cobein, xkiz ™) »
Crear grafico con microsoft chart
Ir a:
Powered by SMF 2.0.4 | SMF © 2006–2009, Simple Machines LLC
XHTM