How to use array in vb.net for combobox usage - vb.net

Let me say that i want to return some array by using this method
Function getKategori() As String()
Dim a As String() = {}
Try
connection.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = connection
myCommand.CommandText = "SELECT * FROM kategori"
myAdapter.SelectCommand = myCommand
reader = myCommand.ExecuteReader
While reader.Read()
a = {reader(0).ToString, reader(1).ToString}
End While
Catch ex As Exception
End Try
Return a
End Function
it should be return as like
{{a,b},{a,b}} etc, and i want to use that result into combo box by using foreach method
For Each k In x.getKategori()
'?some function to add these items into combobox?
Next
How should i do for it?

Related

How to make a default item for ComboBox with a DataSource

In my application I have a data bound ComboBox that looks like this:
Dim listaCategoria As List(Of Ccategoria) = CAD.ObterTodosC()
cbxAlterarCg.DataSource = listaCategoria
cbxAlterarCg.DisplayMember = "nomeCategoria"
cbxAlterarCg.ValueMember = "idCategoria"
The class code (CAD):
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
And the attributes:
Public Class Ccategoria
Private _idCategoria As Integer
Private _nomeCategoria As String
(...)
My ComboBox displays "nomeCategoria" with the "idCategoria" value right.
Now my question, like the title says can I create a default read only item so saying ("select your category") or something like that?
I've seen some other tutorials but none of them with ComboBox which are data bounded.
What you could do is add a Ccategoria() to lstTodos just under Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria) like so:
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
In doing this you are simply adding to the DataSource. You could then look into providing validation by checking to see if idCategoria is 0. If it is you may want to consider showing a MessageBox to the user prompting them to pick a category.

datagridview not showing the first row vb.net

hi so i have this list that im currently using on a combobox that's why i have the idcategoria = 0 with the nomeCategoria = "Select your Category"so the combobox default item would be "select your category".
here is the code of the list
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
Now i want to use the same list on a datagridview and i wanted to know if there is a way to not show the id = 0 on the datagridview or do i have to create another list without the idCategorie = 0 for the datagridview, any ideas on this? thanks
Create another list from already loaded
Dim newList = lstTodos.Skip(1).ToList()
Skip method will return new collection without first item.
Notice that this approach will work only when - Select your Category - item is a first item in the list.
Or change your method to return list without - Select your Category - item and add it only when you need.
Public Shared Iterator Function ObterTodosC() As IEnumerable(Of Ccategoria)
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Yield New Ccategoria With
{
.IdCategoria = reader.GetInt32(0),
.NomeCategoria = reader.GetString(1)
}
End While
End Using
End Using
End Function
Then you can create list of categories for datagridview
Dim forDataGridView = ObterTodosC().ToList()
Dim notSelectedCategory As New Ccategoria With
{
.IdCategoria = 0,
.NomeCategoria = "select your category"
}
Dim forComboBox = forDataGridView.ToList()
forComboBox.Insert(0, notSelectedCategory)
With this approach your remove side effect from ObterTodosC method.
So method responsibility will be only load items from database

How to refresh form after selecting value from combobox

I would like to know if it is possible to refresh the current windows form I am at after selecting another value from the combo box in order to display the details of that item onto several other textboxes?
So my table looks like
table name : program
program_id program_name program_desc
1 T1 desc1
This is the code i am using atm
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "pathway"
Dim dr As SqlDataReader
Dim prognamedesc As String
Dim filetypetxt As String
Dim prognamecombo As String
Dim filetypecombo1 As String
Dim command As New SqlCommand
Dim querycommand As New SqlCommand
connection.Open()
'THIS SECTION LOADS DATA FROM THE TABLES'
Try
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "select program_name,filetype from program order by program_name; select * from filetype"
querycommand.Connection = connection
querycommand.CommandType = CommandType.Text
querycommand.CommandText = "select program_name,program_desc , filetype from program where program_name like" & FiletypeComboBox1.SelectedItem & ""
dr = command.ExecuteReader
While dr.Read()
prognamecombo = dr(0)
Program_nameComboBox.Items.Add(prognamecombo)
End While
dr.NextResult()
While dr.Read()
filetypecombo1 = dr(0)
FiletypeComboBox1.Items.Add(filetypecombo1)
FiletypeComboBox1.SelectedItem = filetypecombo1
End While
dr.NextResult()
While dr.Read()
filetypetxt = dr(0)
FiletypeLabel1.Text = filetypetxt
End While
dr.NextResult()
While dr.Read()
prognamedesc = dr(0)
Program_descTextBox.Text = prognamedesc
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
I was wondering if this is doable using the current code?
To implement this you have to do two things, First put all your code inside a method and call it something like RefreshForm()
public void RefreshForm()
{
// your code and binding goes here
}
The second step is by using selected index changed event over combobox you just call the method that includes all your binding code.

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

get single value from sql-query into a textbox

The result of my sql-query is a single value i want display that in a lable but dont know how. I have a solution creating a dataset put the result of the query into that dataset and get it by row(0),column(0) but i guess there is a smarter way doing it.
Private myquery As String
Sub New(ByVal query As String)
myquery = query
End Sub
Public Sub query_Send()
Dim myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim mycmd As SqlCommand = New SqlCommand(Me.myQuery, myconn)
Dim myTable As New DataTable
Dim previousConnectionState As ConnectionState = myconn.State
Try
If myconn.State = ConnectionState.Closed Then
myconn.Open()
Dim myDA As New SqlDataAdapter(mycmd)
myDA.Fill(myTable)
tb.text = **...**
End If
If previousConnectionState = ConnectionState.Closed Then
myconn.Close()
End If
End Try
End Sub
You can use SqlCommand.ExecuteScalar Method
Dim querystr as String = "select value from MyTable where ID=5"
Dim mycmd As New SqlCommand(querystr, connection)
dim value as Object = mycmd.ExecuteScalar()
The value you can put to your textbox. ExecuteScalar returns first value of first row of the resultset (equivalent of row(0).column(0) ) When no record is returned the value is nothing.
Try something more along the lines of:
Using myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim myDA As New SqlDataAdapter()
myDA.SelectCommand = New SqlCommand(myQuery, myconn)
myDA.Fill(myTable)
Return myTable
End Using
Or you can just get ahold of the first item in the first row with
myTable.Rows(0).ItemArray(0).ToString()