VB.NET: Populating ComboBox Using MySQL Query - mysql

I am trying to populate a Combobox from a MySQL database; but I don't get anything.
Below is the code.
Table: Class
Columns: Code, State
sqlstr = "SELECT * FROM Class WHERE State= Not Started"
DBCmd = New MySql.Data.MySqlClient.MySqlCommand(sqlstr, DBConn)
DBDR = DBCmd.ExecuteReader
While (DBDR.Read())
CB_Class.Items.Add(DBDR("Code"))
End While
DBCmd.Dispose()
DBDR.Close()
I believe the result is wrong, because there are at least 2 records with their state values set as "Not Started". What is wrong? Is there anything wrong with the way I've written "State= Not Started" ?

The command text doesn't seems correct. It lacks the single quote around the string to search
sqlstr = "SELECT * FROM Class WHERE State='Not Started'"
^ ^
If State is a string field then every search over it should be enclosed in single quotes.
Beware of the potential problems when the string to search contains a single quote.
In this simple case you could use directly the string constant, but if you render your search dynamic with user input then you should use parametrized queries.

Related

Error when using textbox values inside string sql

"Select item from table1 where Spare parts='"+ textbox1.text+"'".
I have tried to replace item with Textbox2.text.
I used :
"Select'"& textbox2.text& "' from table1 where Spare parts='"+ textbox1.text+"'"
I got error.
I used "+ textbox2.text+" I got error too
What you have here is one of the fastest ways out there to get your app hacked. It is NOT how you include user input in an SQL statement.
To explain the right way, I also need to include the connection and command objects for context, so I may also have a different pattern for how I handle these than you're use to. I'm also assuming the mysql tag in the question is accurate (though I have my doubts), such that the correct code looks more like this:
string SQL = "Select item from table1 where `Spare parts`= #SpareParts";
using cn = new MySqlConnection("connection string here")
using cmd = new MySqlCommand(SQL, cn)
{
cmd.Parameters.AddWithValue("#SpareParts", TextBox1.Text);
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// ...
}
}
}
Note the backticks around Spare Parts, so it will be correctly treated as a single object name by MySql.

Visual basic datagridview result showing numbers of results not the text

Might be a bad title but as a non-english speaking person not everything is simple.
My problem is the following:
Fetching data from Mysql database (No problem)
Adding a Combobox in my Datagridview (No problem)
Inserting the result into that combobox (Problem)
What happens is that the combobox shows me the number of results, it is showing me 212 as a single possibility to click and not the value of the MySQL cell.
My code looks like this:
'//Henter drivere fra Printer Installer Database //'
mysqlconnpi.Open()
query = "Select model_name from printer_installer.ppp_drivers"
data = New DataTable
dataAdap = New Devart.Data.MySql.MySqlDataAdapter(query, mysqlconnpi)
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "Select Data"
cmb.Name = "cmb"
cmb.MaxDropDownItems = 100
cmb.Items.Add(dataAdap.Fill(data))
DataGridView1.Columns.Add(cmb)
The result is this:
What is wrong with my code?
Also, I found out that the combobox only could handle 100 items, is there a way for my to get more? I currently have 212 drivers in the database I want to list.
EDIT:
I testet to add this line:
DataGridView1.DataSource = data
to the code just to check if "data" even had items.
the result is this:
Not allowed to insert embedded, image is here.
The code is now:
'//Henter drivere fra Printer Installer Database //'
mysqlconnpi.Open()
query = "Select model_name from printer_installer.ppp_drivers"
data = New DataTable
dataAdap = New Devart.Data.MySql.MySqlDataAdapter(query, mysqlconnpi)
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "driver"
cmb.Name = "cmb"
cmb.MaxDropDownItems = 100
cmb.Items.Add(dataAdap.Fill(data))
DataGridView1.Columns.Add(cmb)
DataGridView1.DataSource = data
'DataGridView1.DataSource = dataAdap.Fill(data)
'-------------------------------------------------'
The DataGridView might be looking at the string length which is the property of string the result of the query so you might want to send the result by wrapping your string. You can use linq in place of your sql query.
From model in printer_installer.ppp_drivers select new with {Key .name =model.model_name}

SSIS Convert Blank or other values to Zeros

After applying the unpivot procedure, I have an Amount column that has blanks and other characters ( like "-"). I would like to convert those non-numberic values to zero. I use replace procedure but it only converts one at the time.
Also, I tried to use the following script
/**
Public Overrides Sub Input()_ProcessInputRows(ByVal Row As Input()Buffer)
If Row.ColumnName_IsNull = False Or Row.ColumnName = "" Then
Dim pattern As String = String.Empty
Dim r As Regex = Nothing
pattern = "[^0-9]"
r = New Regex(pattern, RegexOptions.Compiled)
Row.ColumnName = Regex.Replace(Row.ColumnName, pattern, "")
End If
End Sub
**/
but i'm getting error.I don't much about script so maybe I placed in the wrong place. The bottom line is that I need to convert those non-numberic values.
Thank you in advance for your help.
I generally look at regular expressions as a great way to introduce another problem into an existing one.
What I did to simulate your problem was to write a select statement that added 5 rows. 2 with valid numbers, the rest were an empty string, string with spaces and one with a hyphen.
I then wired it up to a Script Component and set the column as read/write
The script I used is as follows. I verified there was a value there and if so, I attempted to convert the value to an integer. If that failed, then I assigned it zero. VB is not my strong suit so if this could have been done more elegantly, please edit my script.
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
' Ensure we have data to work with
If Not Row.ColumnName_IsNull Then
' Test whether it's a number or not
' TryCast doesn't work with value types so I'm going the lazy route
Try
' Cast to an integer and then back to string because
' my vb is weak
Row.ColumnName = CStr(CType(Row.ColumnName, Integer))
Catch ex As Exception
Row.ColumnName = 0
End Try
End If
End Sub

how to change the date format as it not the same with the database

As the coding show at textbox 18/02/2012 (for example). but in database it is 02/18/2012.
TxtReqDate.Text = Calendar.SelectionStart.ToString("dd/MM/yyyy")
cboTermCode.Focus()
Calendar.Visible = False
But when i want to retrieve the related data for the date using coding below :
sqlCbo2 = "SELECT DISTINCT gear_code FROM gear WHERE est_start_date='" & TxtReqDate.Text & "'"
it say invalid date.
i cannot change the date format in the database.
if i change the code TxtReqDate.Text = Calendar.SelectionStart.ToString("dd/MM/yyyy") TO TxtReqDate.Text = Calendar.SelectionStart.ToShortDateString as it will appear 02/18/2012 at the textbox the data will appear but i want 18/02/2012 to appear at the textbox.
You could make use of STR_TO_DATE function to parse that data and transform it into a Date value.
Use it like this (correct any syntactical error):
where do i should put it. example??
sqlCbo2 = "SELECT DISTINCT gear_code FROM gear WHERE est_start_date=STR_TO_DATE('" & TxtReqDate.Text & "','%d/%m/%Y')"
This example is actually using the OleDbCommand but the syntax is similar for the SqlCommand: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Dim comm As New OleDb.OleDbCommand(reportQueryString, conn)
comm.Parameters.Add("[ReportDate]", OleDbType.Date)
comm.Parameters("[ReportDate]").Value = dateVariable
You can see that when you add the parameter, you specify the dataType the command should convert your data type to. This way you're not doing raw string manipulation yourself.

Removing non-alphanumeric characters in an Access Field

I need to remove hyphens from a string in a large number of access fields. What's the best way to go about doing this?
Currently, the entries are follow this general format:
2010-54-1
2010-56-1
etc.
I'm trying to run append queries off of this field, but I'm always getting validation errors causing the query to fail. I think the cause of this failure is the hypens in the entries, which is why I need to remove them.
I've googled, and I see that there are a number of formatting guides using vbscript, but I'm not sure how I can integrate vb into Access. It's new to me :)
Thanks in advance,
Jacques
EDIT:
So, Ive run a test case with some values that are simply text. They don't work either, the issue isn't the hyphens.
I'm not sure that the hyphens are actually the problem without seeing sample data / query but if all you need to do is get rid of them, the Replace function should be sufficient (you can use this in the query)
example: http://www.techonthenet.com/access/functions/string/replace.php
If you need to do some more advanced string manipulation than this (or multiple calls to replace) you might want to create a VBA function you can call from your query, like this:
http://www.pcreview.co.uk/forums/thread-2596934.php
To do this you'd just need to add a module to your access project, and add the function there to be able to use it in your query.
I have a function I use when removing everything except Alphanumeric characters. Simply create a query and use the function in the query on whatever field you are trying to modify. Runs much faster than find and replace.
Public Function AlphaNumeric(inputStr As String)
Dim ascVal As Integer, originalStr As String, newStr As String, counter As Integer, trimStr As String
On Error GoTo Err_Stuff
' send to error message handler
If inputStr = "" Then Exit Function
' if nothing there quit
trimStr = Trim(inputStr)
' trim out spaces
newStr = ""
' initiate string to return
For counter = 1 To Len(trimStr)
' iterate over length of string
ascVal = Asc(Mid$(trimStr, counter, 1))
' find ascii vale of string
Select Case ascVal
Case 48 To 57, 65 To 90, 97 To 122
' if value in case then acceptable to keep
newStr = newStr & Chr(ascVal)
' add new value to existing new string
End Select
Next counter
' move to next character
AlphaNumeric = newStr
' return new completed string
Exit Function
Err_Stuff:
' handler for errors
MsgBox Err.Number & " " & Err.Description
End Function
Just noticed the link to the code, looks similar to mine. Guess this is just another option.