In VB.NET I am trying to use SQL Parameter to send data to SQL Server Database, I am trying to convert string to decimal with following code if the value of the datagridrow is nothing then send 0 or use conversion to decimal argument.
SQL.Addparam("#amt", IIf(IsNothing(DataGridView2.Rows(index).Cells(7).Value), 0, CDec(DataGridView2.Rows(index).Cells(7).Value)))
(SQL and Addparam is called from class I created)
But with this code I get error "System.InvalidCastException: 'Conversion from string "" to type 'Decimal' is not valid.'"
I need help on this please.
Thank you
The specific issue is clearly that your "empty" cell does not actually contain a null reference, i.e. Nothing, but rather an empty String. You would need to test for an empty String as well as or instead of Nothing. If your cell might contain either Nothing, an empty String or a Decimal value, this should work:
Dim cellValue = DataGridView2.Rows(index).Cells(7).Value
SQL.Addparam("#amt",
If(String.IsNullOrEmpty(CStr(cellValue)),
Decimnal.Zero,
CDec(cellValue)))
Note the use of If rather than IIf and an actual Decimal value for the zero. String.IsNullOrEmpty will detect Nothing or an empty String in a single call.
That's really not the best solution though.
It appears that you are using an unbound grid and then looping through the rows and saving each row individually. That is really the wrong way to go. What you should be doing is creating a DataTable with the appropriate schema, populating it from the database if required, binding it to the grid, performing the required edits and then just saving the whole DataTable in one go with a single call to Update on a data adapter.
If you do that then an "empty" cell will contain DBNull.Value and ADO.NET will automatically save NULL to your database. If you don't want NULL values in a column then just set the AllowDBNull property to False and the DefaultValue property to whatever you want instead.
To create the DataTable schema, you can call Fill on a data adapter to do that and populate with data, or you can call FillSchema to not retrieve any data. Alternatively, you can just build the schema yourself.
Related
If I affect a full array to a ListBox, using ListBox1.List = [{1;2;3;4}] for example, the Listbox's .List items keep their correct type (here numbers), but if I use ListBox1.AddItem 5 or Listbox1.List(5) = 6 to set an individual item the type is automatically changed to String.
Sample Code:
Private Sub UserForm_Initialize()
ListBox1.List = [{1;2;3;4}]
ListBox1.AddItem 5
ListBox1.AddItem
ListBox1.List(5) = 6
End Sub
Later on, when comparing values, I get wrong results because numbers are not equals to text (5 <>"5").
Is there any easy (1) way to ensure the type of the list items is not converted to String?
(1) I know I can explicitly make the conversion to String, but I rather keep my values as numbers instead of "numbers-strored-as-text" in the listbox
I guess that will be impossible when using AddItem. According to https://learn.microsoft.com/en-us/office/vba/api/access.listbox.additem, the first parameter is a string, so everything you pass will be converted to a string.
Probably your best bet is to collect all items in an array and assign the array using ListBox1.List. Or you have to live with numbers stored as string...
Update
I mixed the pages up - link to the Access page was wrong.
Anyhow, Documentation is rather poor. It says "valid object" but doesn't define what that means. At least it is not possible to add a object - that throws a type mismatch.
Also, the documentation states that a Variant is returned, but it seems thatis not true - when I try to get the result, the compiler throws an error.
As a conclusion, I assume that AddItem converts everything to a string (and throws an error if that fails). So I still assume that you have to build up an array and assign it to List if you want to have real numbers.
As part of an access application, i retrieve data from sql server. I have a string field that contains ⅝ in one of the rows, and when i attempt to insert that value into an MsAccess recordset, i get an error
Multiple-step operation generated errors. Check each status value. Here is my code
sFieldValue = getValue() ' when i add a watch, the '⅝' is replaced by a ? e.g. "The result is ⅝" will be shown as "The result is ?"
Rs(sFieldName) = sFieldValue ' error is thrown
I then attempted to hard code the value in VBA
sFieldValue ="⅝"
And the moment i type '⅝' it automatically changes to a question mark
sFieldValue ="?"
I would like to know how i can support characters such as "⅝". The other fractions work just fine, e.g. '½'. I do not want to do any calculations, the fractions are part of a string that comes from a SQL Server, and the problem is, i get a runtime error when i try to add a string value that contains a fraction to a recordset in access.
from this page, it shows that some fractions are supported in utf-8
The problem was that the field type of Rs(sFieldName) was adVarChar. So to fix the problem, i used a adVariant field type in my recordset, and it now accepts the ⅝ vulgar character.
I am creating the recordset on the fly.
Edit: adVarWChar is more appropriate, see comment below
I have encountered this problem several times already and have been able to work around it till now. Also the almighty search engines didn't help me.
The problem is that when I have populated a listbox or combobox from a ADODB recordset all Decimal data elements are not visible in the box, for example with the following (conn is a ADODB connection):
Private Sub GetFilteredRecords()
Dim strSQL As String
Dim arr As Variant
'create the SQL
strSQL = "SELECT * FROM vwStandard_Fee2"
'execute the SQL and fill the rs ( rsFiltered )
Set rsFiltered = conn.Execute(strSQL)
'Apply recordset to the listbox on the form
If Not (rsFiltered.EOF = True And rsFiltered.BOF = True) Then
arr = rsFiltered.GetRows()
With lbDeeper
.ColumnCount = rsFiltered.Fields.Count
.List = TransposeArray(arr)
End With
With cbDeeper
.ColumnCount = rsFiltered.Fields.Count
.List = TransposeArray(arr)
End With
End If
End Sub
Above contains 6 columns of Ids (all show Type = Variant/Decimal), of which the containing values are all not "shown" for some strange reason. Only the String and Date columns are shown normally, the Decimals are there but empty!
Here some snippets:
Now in case of a combo box I can get one column's value shown if their column the BoundColumn when I select that listitem, but only in the value fo the combobox (so still not in the list).
My initial workaround was to convert them into String values before adding to the Listbox/Combobox, in this case however I want to directly link the query result to the Box.List without looking at the details. And thus I am looking for a solution in stead of a work around.
In short: my numerical field items are invisible BY DEFAULT for some strange reason. Workaround was to make the items String values. I am now looking for a solution for this bug/problem instead:
What is causing this?
How to solve it?
So all string data is appearing? And,only numerics don't appear?
Then you may want to convert your numerics to strings and pass it to your list, combo boxes.
Which you have already done I noticed.
Now for any reason if your max number of rows and length of array/recorders row count doesn't match it could also cause an issue. However it seems your setting rows of combobox using recordset row count. Instead of using an array can you try to iterate over the recordset to populate the combobox? yes this is not performance friendly, buy guess what we need it to work without bugs before optimizing. ;-)
Have you bound your combobox to the recordset? Can you confirm if your array is single dimension and it has data to feed to the box?
You may try to populate the listbox using a saved query in the DB to if the issue still persists.
However, list boxes and combo boxes based on SQL statements are slower than
list boxes and combo boxes based on saved queries.
So can you try the following to set rowsource property? Make sure to test on both number,and test columns. As well as on old combo box and new one.
Rowsource->build query->
sqlview copy to rowsource property box->
delete or don't save that above built query since you already have SQL statement.
Just wanted you to try out possibilities to narrow down the issue.
UPDATING ANSWER WITH MOST POSSIBLE ISSUE AND SOLUTIONS
As per my comments, they mainly given assuming you had issues populating listbox/combobox
I forgot to ask something very very important, have you declared
Option Base 1 to make sure to avoid losing one of the array's column
values if you are dumping 2D array...? because you do not have any
explicit declartion for the array you are using to dump data into the
listbox.......... :)
Make sure your Listbox is enabled to show multi column data.
*So you have three choices, *
Option Base 1
ReDim your array and do looping to fill it and dump it into .list.
Since ReDim array need you to anyway loop through, you may just as well
use the recorset iself to add the data.
You seem to have a dimension issue with the array which is not declared but transposed from recordset and then to listbox/combobox. So your undeclared array is not populating multi-columns properly. That could be the reason it works when you declare array proeprly.......
Infact in your comment you have said so,
When I create an array in my code and populate it in my code (entry by
entry) it will show without any problem – K_B 14 mins ago
OK after going through various possible causes it seems to be the case that:
VBA has no Decimal Variant Type of its own.
VBA can handle Decimal from within a variable declared as Variant (thus becoming a Variant/Decimal)
This normally doesn't stop your program from working, but in Controls like Listbox and Combobox the Type Variant/Decimal is not interpretable and thus wont draw that specific entry.
For example populate a listbox called lbHigher with this:
Private Sub ListBoxProblem()
Dim tempArray(2, 2) As Variant
tempArray(0, 0) = "A"
tempArray(0, 1) = 1
tempArray(0, 2) = 1.1
tempArray(1, 0) = "B"
tempArray(1, 1) = CStr(CDec(5.2))
tempArray(1, 2) = 2.3
tempArray(2, 0) = "C"
tempArray(2, 1) = DateSerial(2012, 12, 13)
tempArray(2, 2) = 100
tempArray(3, 0) = "D"
tempArray(3, 1) = -1
tempArray(3, 2) = CDec(5.2)
lbHigher.ColumnCount = 3
lbHigher.List = tempArray
End Sub
Everything works fine except for the CDec(5.2). The CStr(CDec(5.2)) works fine as well as VBA will first have converted the Decimal to String before the Listbox gets to get it.
So either: Dont let the SQL generate any Decimal output OR convert any Decimal output to Single/Double/String/Integer/Long in VBA before handing it to the Listbox.
I'm trying to create a custom script in SSIS 2008 that will loop over the selected input columns and concatenate them so they can be used to create a SHA1 hash. I'm aware of the available custom components but I'm not able to install them on our system at work.
Whilst the example posed here appears to work fine http://www.sqlservercentral.com/articles/Integration+Services+(SSIS)/69766/ when I've tested this selected only a few and not all columns I get odd results. The script only seems to work if columns selected are in sequential order. Even when they are in order, after so many records or perhaps the next buffer different MD5 hashes are generated despite the rows being exactly the same throughout my test data.
I've tried to adapt the code from the previous link along with these articles but have had no joy thus far.
http://msdn.microsoft.com/en-us/library/ms136020.aspx
http://agilebi.com/jwelch/2007/06/03/xml-transformations-part-2/
As a starting point this works fine to display the column names that I have selected to be used as inputs
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
For Each inputColumn As IDTSInputColumn100 In Me.ComponentMetaData.InputCollection(0).InputColumnCollection
MsgBox(inputColumn.Name)
Next
End Sub
Building on this I try to get the values using the code below:
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Dim column As IDTSInputColumn100
Dim rowType As Type = Row.GetType()
Dim columnValue As PropertyInfo
Dim testString As String = ""
For Each column In Me.ComponentMetaData.InputCollection(0).InputColumnCollection
columnValue = rowType.GetProperty(column.Name)
testString += columnValue.GetValue(Row, Nothing).ToString()
Next
MsgBox(testString)
End Sub
Unfortunately this does not work and I receive the following error:
I'm sure what I am trying to do is easily achievable though my limited knowledge of VB.net and in particular VB.net in SSIS, I'm struggling. I could define the column names individually as shown here http://timlaqua.com/2012/02/slowly-changing-dimensions-with-md5-hashes-in-ssis/ though I'd like to try out a dynamic method.
Your problem is trying to run ToString() on a NULL value from your database.
Try Convert.ToString(columnValue) instead, it just returns an empty string.
The input columns are not guaranteed to be in the same order each time. So you'll end up getting a different hash any time the metadata in the dataflow changes. I went through the same pain when writing exactly the same script.
Every answer on the net I've found states to build a custom component to be able to do this. No need. I relied on SSIS to generate the indexes to column names when it builds the base classes each time the script component is opened. The caveat is that any time the metadata of the data flow changes, the indexes may change and need to be updated by re-opening and closing the SSIS script component.
You will need to override ProcessInput() to get store a reference to PipelineBuffer, which isn't exposed in ProcessInputRow, where you actually need to use it to access the columns by their index rather than by name.
The list of names and associated indexes are stored in ComponentMetaData.InputCollection[0].InputColumnCollection, which needs to be iterated over and sorted to guarantee same HASH every time.
PS. I posted the answer last year but it vanished, probably because it was in C# rather than VB (kind of irrelevant in SSIS). You can find the code with all ugly details here https://gist.github.com/danieljarolim/e89ff5b41b12383c60c7#file-ssis_sha1-cs
I'm fairly new to using Visual Basic. And I have never worked with databases/datatables before now.
On my datatable (I hope that's the correct word) I have two columns that I want to store color values. I changed the data type to "System.Drawing.Color".
However it would appear I cannot simply type in the string (e.g: "Color.Black") to add it to the database. And when using an update SQL query and make it look for color values on the form, it wants to convert them to string.
Is it possible to store color values like this in this way or do I have use another method?
All colors are presented by a string on either "Color.Black" or "#000000", so the only thing you can do is convert it to a string when you put into DataTable, then convert it back to a color when you retrieve it from the Datatable