Why retrieving a string with a character dot(.) does not get properly - vb.net

I have an inventory in Visual basic that get the product name and the unit name in the database which is Microsoft Access. Everything is fine except when I retrieve a string with a character dot(.). When i retrieve a unit with a dot, the dot is place in the first index of my string.
Here is my UnitList table
And this is what I get when i select an item with pcs. unit. It should be "pcs.".
The dot(.) character is place in first index of my string. Same result with other unit with a character dot.
Here is my code:
Sub GetIngredientUnit(ByVal ProductName As String, ByVal Store As Label)
con.Close()
con.Open()
Query = "SELECT UnitList.UnitName FROM UnitList INNER JOIN ProductStock ON UnitList.[UnitID] = ProductStock.[UnitID] where ProductName = '" & ProductName & "'"
cmd = New OleDbCommand(Query, con)
Store.Text = cmd.ExecuteScalar
End Sub
And i call the code :GetIngredientUnit(ListViewInvStock.SelectedItems(0).Text, INVUnit) when the index of ListBox change

Change the Label's RightToLeft property to No. This property indicates if the language in use is a right-to-left script (e.g. Arabic).
If you want to align the text to the right hand side, set the TextAlign property instead.

Related

Chinese characters in Access SQL Query

After populating the recordsource the next action is clicking on one of the fields populated to "activate" the record. When clicking this, the goal is that the SEC_ID (A GUID, Number Data Type) is stored as a tempvar and used in future queries. This GUID is also placed in a text box just for a visual debug. However it doesn't put the GUID, it puts random Chinese characters. I've tried to place it into a MsgBox just to also see and it spits out "???????".
My code to populate the rowsource:
Dim componentListSQL As String
If FCSUtilities.AssessmentUoM = "Metric" Then
componentListSQL = "SELECT DISTINCT [100b_Working].SEC_SYS_COMP_ID, [100b_Working].SEC_ID, [110b_RO_Material_Category].MAT_CAT_DESC, [110b_RO_Component_Type].COMP_TYPE_DESC, [110b_RO_Material_Category].MAT_CAT_ID, [110b_RO_Component_Type].COMP_TYPE_ID, [100b_Working].ID_Number, [100b_Working].Model, [100b_Working].Serial_Number, [100b_Working].Capacity, [100b_Working].Manufacturer, [100b_Working].SEC_YEAR_BUILT, ROUND([100b_Working].SEC_QTY, 0) AS SEC_QTY, [100b_Working].UOM_MET_UNIT_ABBR, [100b_Working].UOM_ENG_UNIT_ABBR, [100b_Working].Equipment_Make, [100b_Working].UOM_CONV " _
& "FROM (110b_RO_Units_Conversion INNER JOIN (110b_RO_Component_Type INNER JOIN (110b_RO_Material_Category INNER JOIN 110b_RO_CMC ON [110b_RO_Material_Category].MAT_CAT_ID = [110b_RO_CMC].CMC_MCAT_LINK) ON [110b_RO_Component_Type].COMP_TYPE_ID = [110b_RO_CMC].CMC_CTYPE_LINK) ON [110b_RO_Units_Conversion].UOM_ID = [110b_RO_CMC].CMC_UoM) INNER JOIN 100b_Working ON [110b_RO_CMC].CMC_ID = [100b_Working].SEC_CMC_LINK " _
& "WHERE ((([100b_Working].SEC_SYS_COMP_ID) = [Forms]![200a_MainWindow]![txtDebugCompSysID]) And (([100b_Working].SEC_ID) Is Not Null)) " _
& "ORDER BY [110b_RO_Component_Type].COMP_TYPE_DESC;"
Me![210_ComponentList].Form.RecordSource = componentListSQL
End If
The OnClick event:
Private Sub txtMaterialCategory_Click()
Me.txtActiveSecID.Value = Me.txtSecID.Value
End Sub
The txtSecID appears as a GUID as it should but it's in the txtActiveSecID that it becomes Chinese characters even if I attempt to put it as a tempvar then set it into the txtActiveSecID.
I'm not exactly sure what is going on. Looking at different stacks, it points that it's due to long/memo field but as I said previously, the SEC_ID field data type is Number.
Per MS documentation https://learn.microsoft.com/en-us/office/vba/api/Access.Application.StringFromGUID:
The Microsoft Access database engine stores GUIDs as arrays of type Byte. However, Access can't return Byte data from a control on a form or report. To return the value of a GUID from a control, you must convert it to a string. To convert a GUID to a string, use the StringFromGUID function. To convert a string back to a GUID, use the GUIDFromString function.
StringFromGUID(Me.txtSecID.Value)
However that results in output like:
{guid {2786C27B-CB7C-4DEA-8340-1338532742DE}}
That should still work as filter critera but could do further processing to extract GUID from that string. Use string manipulation functions to remove the {guid header and trailing }. Review Access - GUID value stored in textbox, can't be used in SELECT statements

Is there any SQL Statement procedure or code for optional requested field value?

I'm a beginner. I created a database in vb.net and I need to build a query, in the SQL Statement - Table Adapter, which returns records even if parameters are NULL in one or more textbox. To be clear, I have several textboxes (related to fields) with which I can filter record results and I want to refine my research as much as I fill textboxes, reverse if I fill just one of them randomly.
Sorry if I confused you, but I guess you get it anyway.
In its simplest form (assuming SQL server param concepts)
-- Define your columns to pull back/display
select t1.column1, t1.column2, t1.column3...
-- Define the table, give it an alias if you're using more than one or it has a silly name
from thetable t1
-- Apply filters
where
-- For each textbox/column search combo, do this...
(column1 = #field1 or #field1 is null)
or -- If the filter is restrictive, use AND here
(column2 = #field2 or #field2 is null)
or -- If the filter is restrictive, use AND here
...
I would dump the table adapter for this requirement.
I am building the sql string using a StringBuilder. StringBuilder objects are mutable, String is not.
To run this Code
1. I assumed Sql Server. If this is not the case change all the data object (Connectio and Command) to the proper provider.
Add your connection string to the constructor of the connection.
Add your table name where it says "YourTable"
I just used TextBox1 etc. as control names. Use your actual control names
Replace Field1, Field2 etc. with your actual column names.
The parameter names (by convention, they start with #) can be anything you want as long as they match the name you add to the Parameters collection.
You will have to check your database for the actual datatypes of the fields. Be sure to convert the TextBox values to the compatible type. TextBox.Text is a string so it will be compatible to .VarChar but note number types or dates.
I added a Debug.Print to check what the Sql string looks like. Be cautious about where I have spaces when building the string. You can see the result in the immediate window (available from Debug menu).
If you don't already have a DataGridView on your form, add one so you can see the reults of your query.
Finally, always use parameters, use Using...End Using blocks, and open your connection at the last minute.
Private Sub RunDynamicQuery()
Dim sb As New StringBuilder
Dim AndNeeded As Boolean
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand
sb.Append("Select * From YourTable Where ")
If Not String.IsNullOrEmpty(TextBox1.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
sb.Append("Field1 = #Field1")
cmd.Parameters.Add("#Field1", SqlDbType.Int).Value = CInt(TextBox1.Text)
AndNeeded = True
End If
If Not String.IsNullOrEmpty(TextBox2.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox2.Text) Then
If AndNeeded Then
sb.Append(" And")
End If
sb.Append(" Field2 = #Field2")
cmd.Parameters.Add("#Field2", SqlDbType.VarChar).Value = TextBox2.Text
AndNeeded = True
End If
If Not String.IsNullOrEmpty(TextBox3.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox3.Text) Then
If AndNeeded Then
sb.Append(" And")
End If
sb.Append(" Field3 = #Field3")
cmd.Parameters.Add("#Field3", SqlDbType.VarChar).Value = TextBox3.Text
AndNeeded = True
End If
sb.Append(";")
cmd.Connection = cn
Debug.Print(sb.ToString)
cmd.CommandText = sb.ToString
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub

Excel to VB: Can't read the zero behind

I'm doing a connection with excel and I have a problem when I try to use an ID that have 0 behind...
I'm using a ListBox and add the IDs from the excel's worksheet as items. IDs have 9 numbers, like "123456789" or "098765430". So that I remove the last 4 characters to search the IDs with the same 5 numbers and add in another ListBox. It works fine, except with the codes with 0 (zero) behind.
Dim ConnectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\Tabela_Precos.xlsx; Extended Properties=Excel 12.0;")
ConnectionString.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da
For i = 0 To Form1.ListBox1.Items.Count - 1
Dim str As String = Compras.ListBox1.Items(i).ToString
Dim prod As String = str.Remove(str.Length - 4)
da = New OleDbDataAdapter("SELECT * FROM [Sheet1$] WHERE ID like '%" & prod & "%'", ConnectionString)
ListBox1.Items.Add(dt.Rows(i).Item(0))
Next
Your Excel file has the ID column entered as integer values, but is formatted for left-zero padding to present as a nine character field. Your Excel db connection is reading the values as numbers (type Double, even-though they are integers). Your original select statement is implicitly convert ID to a string for the Like comparison; however, this conversion does not now you want left-zero padding. To use this type of comparison, you need to format ID yourself.
Select * From [sheet1$] Where (Format([ID], ""000000000"") Like '" & prod & "%')"
As you have indicated in the comments above, this works. However, it is not the most efficient in terms of speed. Since ID is numeric, it should be faster to do a numeric comparison. You have already defined a String variable named prod and the following solution uses that variable to prepare a numeric value for use in constructing an alternate select based on your criteria.
Dim prodNum As Int32 = Int32.Parse(prod) * 10000I
Then the Select statement would become:
"Select * From [sheet1$] Where ((([ID]\10000) * 10000)=" & prodNum.ToString & ")"
These examples use a concatenated select statement, and ideally you would not do it this way, but rather use a parameterized statement with replacement values. I'll leave that exercise up to you to perform.

Populate listbox with alias values using SQL select statment

I have two columns in MS SQL table (ID, and Name) that I want to use to populate a list box with. I would like to show the Name values (as alias?) in the list box, however when the user selects the item I want the ID value to be returned not the Name value. My code below just adds the values into the list box from the Name column.
Me.listName.Items.Clear()
Dim strName As String = "select SetName from " & tb
Dim con As String = sConnectionString
Dim com As New SqlCommand(strServiceType, New SqlConnection(con))
com.Connection.Open()
Dim dr As SqlDataReader
Dim ColumnValue As String = Nothing
dr = com.ExecuteReader
While dr.Read
ColumnValue = (dr.GetValue(0)).ToString
listName.Items.Add(ColumnValue)
listName.Sorted = True
End While
com.Connection.Close()
I'm not sure how to apply the logic above to get the associated ID value besides running another select statement on the list box SelectedIndexChanged event.
Thank you
If I'm not mistaken, you simply need to edit your sql to pull both ID and Name, then edit your addition of an item to your list box to add a new list item instead.
i.e.
listName.Items.Add(New ListItem("TEXT","VALUE"))

how to get data to textbox from the database

I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.