how to sorting item in combo box by Alphabet - vb.net

i use this code to fill the search result records in combo pox and it working good ..
da = New SqlDataAdapter("Select * From MovTable where NameOfMov like '" & AlphaCB.Text & "%'", sqlcon)
da.Fill(dt0)
SearchResultCbB1.DataSource = dt0
SearchResultCbB1.ValueMember = "NameOfMov"
but i need some change to make the combo pox sorting them by Alphabet
thanks

When you attach a ComboBox's datasource to a datatable (dt0) it actually attaches to the .DefaultView DataView of the table. This means you can set the .Sort property of the view to sort the combo:
dt0.DefaultView.Sort = "[NameOfMov] ASC";
SearchResultCbB1.DisplayMember = "NameOfMov" 'this shows in the combo
SearchResultCbB1.ValueMember= "ID" 'you probably want an ID, not the movie name, for this
SearchResultCbB1.DataSource = dt0
You can change this Sort property at any time. For more info on what you can do with it, see the documentation
Please don't write SQL's like you have there; it's a massive security flaw. For more info on why, read http://bobby-tables.com - it will also give advice on how to prevent it, but really you should look at upgrading your knowledge to use Entity Framework or Dapper for your data access and never again, ever concatenate a value into an SQL string

Please always use parameters to avoid sql injection and make you your sql query strings easier to write. I had to guess the datatype and size of the parameter. Please check your database for the actual values and adjust the code.
The user interface is updated after the database objects are closed and disposed with the Using...End Using block.
Private Sub OPCode()
Dim dt0 As New DataTable
Using sqlcon As New SqlConnection("Your connection string"),
da As New SqlDataAdapter("Select * From MovTable where NameOfMov like #Name Order By NameOfMov;", sqlcon)
da.SelectCommand.Parameters.Add("#Name", SqlDbType.NVarChar, 400).Value = AlphaCB.Text & "%"
da.Fill(dt0)
End Using
SearchResultCbB1.DataSource = dt0
SearchResultCbB1.DisplayMember = "NameOfMov"
SearchResultCbB1.ValueMember = "MovieID" 'The Primary Key field in you Database
End Sub

this is an alternative right answer for my question
da = New SqlDataAdapter("Select * From MovTable where NameOfMov like '" & AlphaCB.Text & "%' order by NameOfMov ", sqlcon)
All I needed was this one addition "order by NameOfMov"
Didn't need all this hassle.

Related

Deleting SQL datarow from a table swipes position of first and second row in vb.net

adding updating everything is fine even delete command is working but the strange part is after executing del command from vb.net application it swipes the position of EMPLOYEE_IDAND NAMEit shows normally in datagridviewafter adding or updating but specifically after deleting the record position of these to column changes until I stop the application and re run the entire project for debugging
Dim con As New MySqlConnection("server=localhost; user=root; password=Masoom1; database=airtech_db; convert zero datetime=true;")
Dim cmd As New MySqlCommand
Dim dt As New DataTable
Dim da As New MySqlDataAdapter
Dim sql As String
Dim DR As MySqlDataReader
Dim SQL_CMD_TXT As String
SQL_CMD_TXT = "DELETE FROM `employees` WHERE (`EMPLOYEE_ID` ='" &
EMPLOYEE_DEL_FRM.DEL_ID_TXT.Text & "'); SELECT * FROM `employees`;"
EMPLOYEE_DEL_FRM.Controls.Add(OBJECT_DATAGRIDVIEW)
With OBJECT_DATAGRIDVIEW
.Size = New Size(587, 242)
.Location = New Size(221, 171)
End With
Try
'DB CMD EXECUTION
con.Open()
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
'Command for datagridview object
With OBJECT_DATAGRIDVIEW
.DataSource = dt
'Scroll to the last row.
.Name = "MYDATAGRIDVIEW"
.FirstDisplayedScrollingRowIndex = .RowCount - 1
End With
con.Close()
Catch ex As Exception
Dim MEB = MessageBox.Show("ERROR FOR SQL CMD EXECUTION SECTION-" & ex.Message,
"SQL CMD EXECUTION", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
attaching the normal and after delete result in images
enter image description here
I am not sure I completely understood your problem, but your problem could that the datagridview generates the columns automatically. See: DataGridView.AutoGenerateColumns
Instead of doing SELECT * FROM is would better to select just the fields you need. If you add more fields to your table in the future, the columns in the datagridview may be displaced because they are in no particular order.
Rather than add the datagridview to your form at runtime:
EMPLOYEE_DEL_FRM.Controls.Add(OBJECT_DATAGRIDVIEW)
I would add it directly in the form layout (so you can see it at design time), and then customize it, bind each column to a database field. The appearance of the grid will be more predictable. Here is a small guide: How to bind datatable/list to datagridview with headers?
Relying on AutoGenerateColumns is not a great idea, because this will show all columns (usually not desirable) and not necessarily in the order that you want.
Other remarks:
Records can be edited or deleted directly in the datagridview, by simply selecting one or more rows, and pressing the Del key. Then just invoke the DataAdapter to commit the changes to the database. You should not even be doing DELETE FROM. Just let the user use the datagridview. The benefit is that if the user makes a mistake, you can roll back changes because you are using a datatable. Here you are deleting immediately and without warning.
Don't do stuff like:
SQL_CMD_TXT = "DELETE FROM `employees` WHERE (`EMPLOYEE_ID` ='" &
EMPLOYEE_DEL_FRM.DEL_ID_TXT.Text & "'); SELECT * FROM `employees`;"
Use parameterized queries instead, this code is insecure and will choke on single quotes or special characters (try it !). Here is a simple example: FAQ: How do I make a parameterized query in the database with VB.NET?. Please use parameterized queries from now on, don't develop bad habits that will always bite you sooner or later. The security risk alone is too high.
Also I am wondering why you did stacked queries. It would better to separate the SELECT from the DELETE.
In this code variable sql is not needed:
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
Just use SQL_CMD_TXT directly. Otherwise it makes the code more difficult to follow.

Read Value from Database in TextBox when Combobox text changes VB.NET

I have a list of Users Names in ComboBox and Some TextBoxes. When ComboBox text changes (i.e I select some username from ComboBox), The TextBoxes are filled with user details from the database.
I have code to achieve this in SQL Database. But these queries are not working with MsAccess database.
MysqlConn = New MySqlConnection
Mysql.ConnectionString = "server=localhost;user=root;password=root;database=database"
Dim READER As MySqlDataReader
Try
MysqlConn.open()
Dim Query As String
Query("select * from database.usernames where name='" & ComboBox1.Text & "'")
Command = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetString("name")
End While
End Try
Here is my answer. Please don't get overwhelmed by it. ;)
Broken code
First of all, as I see it, the code you provided cannot work at all, because:
your Query variable is initialized in an invalid (or at least a very exotic) way. You probably want to use something like:
Dim Query As String
Query = "select * from database.usernames where name='" & ComboBox1.Text & "'"
or in a single line:
Dim Query As String = "select * from database.usernames where name='" & ComboBox1.Text & "'"
you try to assign the connection string to the ConnectionString property of a nonexistent Mysql variable. Or the variable exists because it is declared somewhere else, which might be a bug in your code snippet here. But I assume you want to assign the connection string to the MysqlConn.ConnectionString property instead.
you have not declared the MysqlConn and Command variables anywhere. You only just assign to them. (I will simply assume you have declared the variables correctly somewhere else in your code...)
the IDataRecord interface does not provide a GetString(name As String) method overload. So unless you have defined a custom extension method for it, you probably need to use the IDataRecord.GetOrdinal(name As String) method as well, or use the column index instead of the column name.
Anyway, the code you provided uses MySQL. So I assume that MySQL is the "SQL Database" you are using successfully. And that seems to work, as you say? Well... Hmmm... Then I will simply assume your code snippet is completely correct and works perfectly with MySQL... :/
MS Access vs. MySQL
Using MS Access requires other data access classes (probably the ones in namespace System.Data.OleDb) and another connection string. You could take a look at this ADO.NET OleDb example for MS Access in the Microsoft documentation.
You probably even have to update your SQL query, because every database system uses its own SQL dialect. You might want to consult the Office documentation for that. But your query is quite simple, so perhaps all you have to do to make it work with MS Access is:
remove the database name and use only the table name, and
delimit the name identifier (since it is a reserved keyword in MS Access).
I personally delimit all identifiers in my SQL queries, just to avoid unintended conflicts with reserved keywords. So I would personally use something like this:
select * from [usernames] where [name] = '...'
Additional tips
Also, I would like to provide you some additional (unrelated) tips regarding improving your code:
Use Using-statements with variables of an IDisposable type as much as possible. Those types/classes do not implement that interface if there isn't a good reason for it, so I consider it not unimportant to call Dispose when you are done with such disposable objects (or using a Using statement to call Dispose implicitly).
Use SQL parameters (if possible) to avoid SQL injection vulnerabilities. Look at this StackOverflow question and its answer for an example of how to use SQL parameters with MS Access.
Example
You may take a look at the following code snippet. It might not provide a working example out-of-the-box, but you might get some useful/practical ideas from it:
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\database.mdb;User Id=admin;Password="
Dim query As String = "select * from [usernames] where [name] = #Name"
Using conn As New OleDbConnection(connectionString)
Using command As New OleDbCommand(query)
command.Parameters.Add("#Name", OleDbType.VarChar, 50).Value = ComboBox1.Text
conn.Open()
Using reader As OleDbDataReader = command.ExecuteReader
If reader.Read Then
textbox1.Text = reader.GetString(reader.GetOrdinal("name"))
End If
End Using
End Using
End Using

Unwanted name column in DataGridView - How can I get rid of it?

I'm making a WinForms application using VB.NET. I have a DataGridView that I am using to display results of a query to an SQL-Server Database. This works fine:
Dim SQL As New SqlConnection()
Dim CMD As New SqlCommand()
Dim ADP As New SqlDataAdapter()
Dim TBL As New DataTable()
SQL.Close()
SQL.ConnectionString = "Server=" & GetServerIP() & ";Database=" & GetDB() & ";User Id=" & userID & ";Password=" & pass & ";"
CMD.Connection = SQL
CMD.CommandText = "SELECT * FROM " & table
SQL.Open()
ADP.SelectCommand = CMD
TBL.Clear()
ADP.Fill(TBL)
DataGridView1.DataSource = TBL
The issue is that the DataGridView has a column NAME which is empty in every row.
I tried changing the query to SELECT SEQ_NUM FROM CONFIG_SYS that resulted in a DataGridView with a NAME and SEQ_NUM column. I tried calling DataGridView1.Columns.Clear() before the DataGridView1.DataSource = TBL and that does not have an effect on anything. I should mention that if I query any table in my database that does not have a NAME column, I get the same results with an empty NAME column in my DataGridView.
My theory is that a DataGridView automatically adds NAME as the first column, expecting the Database Table to be set up with a NAME column as the primary key. However, my table does not have NAME, it has a column called SEQ_NUM as the primary key. I am able to work around this by doing DataGridView1.Columns("NAME").Visible = False but I don't feel that this is the best way to do it.
Is there a better way to handle this - I'd like the column to not exist at all in the data grid, not just not be visible.
What was causing my issue was the fact that I was calling TBL.Clear() incorrectly.
Calling DataTable.Clear() will clear the Data from a DataTable but it will leave the columns in place.
Instead I should have been calling TBL.Columns.Clear(), which gets rid of the columns of the DataTable. However, using Breakpoints and Visual Studio's DataTable Visualizer I noticed that only calling TBL.Columns.Clear() left the empty rows still in the DataTable. Therefore, to answer the question of how to get rid of a column in a DataGridView that you don't know why/how is there, I suggest to call:
DataTable.Clear()
DataTable.Columns.Clear()
Before setting your DataGridView equal to your DataTable.
Taken from the MSDN:
The .Clear() Method of a DataTable Class "clears the DataTable of all data."
The DataTable.Columns Property gets "a DataColumnCollection that contains the collection of DataColumn objects for the table"
The DataColumnCollection Class also has a .Clear() Method which "clears the collection of any columns."
Thank you #TnTinMn for pointing me in the right direction by using breakpoints and #LarsTech for making me realize that I harshly mixed up DataGridView and DataTable in my original answer.
I hope this post can help others prevent themselves from ripping their hair out about where a non-existent column in their databases seemingly materialized from... If this does not fix your specific issue. I would also check the Query, Database Table setup, and the DataGridView; but for me the issue was with the DataTable.

please help retrieving data to put it on label

I want to retrieve the price from table Products to use it as label2 on the orderinfo form.
Dim con As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
com = New OleDb.OleDbCommand("Select Price FROM Products WHERE ProductName='" & ListBox1.SelectedItem.ToString & "'", con)
con.ConnectionString = "PROVIDER = Microsoft.ACE.OLEDB.12.0; Data Source=Database_AntoninosCafe.accdb"
con.Open()
com.ExecuteNonQuery()
orderInfo.Label2.Text = retrieve data
con.Close()
The correct approach to your simple problem
Dim cmdText = "Select Price FROM Products WHERE ProductName=?"
Using con = New OleDb.OleDbConnection( ... connection string here ...)
Using com = New OleDb.OleDbCommand(cmdText, con)
com.Parameters.AddWithValue("#p1", ListBox1.SelectedItem.ToString)
con.Open()
Using reader = com.ExecuteReader()
if reader.Read() Then
orderInfo.Label2.Text = reader("Price").ToString
End If
End Using
End Using
End Using
The first thing is to use a parameterized query to avoid sql injections and parsin problems, then use the Using statement to encapsulate you disposable object in a block of code that ensures the closing and disposing of these objects.
Finally, to read data from a datatable you use the ExecuteReader command that returns an OleDbDataReader instance. It is this instance that could be used to extract the data from your database
As a side note, I have used, as placeholder for the parameter, a question mark. This is the predefined symbol used by OleDb. But, when adding the parameter value to the collection, I have used a different name (#p1). This is acceptable because OleDb do not use the parameter names to find the corresponding placeholders in the query text like the SqlClient or other providers, but use the position of the placeholder. So, first placeholder replaced by the first parameter and so on.

VB.net Query results

I'm a bit confused on how to grab query results. With VBA i would open a record set and have the results of the query written to that recordset. IN VB.net how can I grab the query result and throw each column into specfic arrays?
dim ssql as string
ssql = " Select * from table "
Now how would I force it to query my DB? I have a connection established already.
After the query how can i play with the columnes and place them into arrays?
This is actually a pretty big topic...you might want to get an overview before you start.
http://msdn.microsoft.com/en-us/library/h0y4a0f6(v=vs.80).aspx
To answer your question: If you have a database connection you can use a DataAdapter to fill a local dataTable or dataSet.
connectionString = "Data Source=servername; Initial Catalog=databasename; " + _
"User ID=userid; Password=password"
cnn = New SqlConnection(connectionString)
cnn.Open()
sqlAdp = New SqlDataAdapter("select * from users", cnn)
sqlAdp.Fill(ds)
EDIT: This is just a sample, you'll want to close the connection and declare a dataSet 'ds'.
You should take a few minutes to read this