How to dynamically the label number - vb.net

This is a tennis tournament simulation program I'm Trying to make a tree. Everything its working perfectly but I have a big problem. I can't progress to the next stage with the winners of the firts games. Because I can't change the "target" label where I want to write the winners name. Here's a print:
This is how I Generate the winners who is going to the next stage and it actually works.~
Public Sub Gerar_Vencedor(Atleta1, Atleta2)
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;" &
"Data Source = E:\dev\Ganso\BaseDados_ClubeTenis.accdb"
con.Close()
con.Open()
Dim busca = "Select Vencedor From Jogo Where idAtleta1 = '" & Atleta1 & "' and idAtleta2 = '" & Atleta2 & "'"
Dim cmd As OleDbCommand = New OleDbCommand(busca, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
' A variável sql vai receber a string para fazer o select a base de dados
'Try
' é aberta ligação a Bdados
' declaração de um comando que vai executar a instrução sql na base de dados
' variável que vai receber os registos resultantes da instrução sql
' ciclo que vai percorrer todos os registos do comando anterior
While dr.Read()
Label9.Text = dr("Vencedor")
End While
con.Close()
End Using
End Sub
My problem is that Label9.Text = dr("Vencedor") because everytime I get a winner it goes to label9.
My final question is: Is there anyway to dynamically change the label without repeating this function over and over.
Thanks.

Can You Try
Dim i As Integer = 9
While dr.Read()
If i < 15
DirectCast(Me.Controls("Label" & i), Label).Text = dr("Vencedor")
Else
End If
i = i + 1
End While

Related

Error In getting data from DataTableReader

as title say's im not being able to get my data from datatable, it's because im using innerjoin , if i only use one table it work's fine, as soon as i put inner join it gives me this error :
seems like the error its in sql sentence, because it don't return any value to datareader.
"System.InvalidOperationException: 'O DataTableReader é inválido para o DataTable atual ''.'"
here goes the code
Dim sql As String = "SELECT * FROM TOTAIS INNER JOIN FAT_PRODS ON TOTAIS.ID_FAT=FAT_PRODS.ID_FAT WHERE FAT_PRODS.ID_FAT=" + DataGridView1.SelectedRows(0).Cells(1).Value.ToString + ""
Dim dadosretornados As System.Data.DataTableReader = buscadadosacess(sql)
If dadosretornados.HasRows Then
While dadosretornados.Read
MsgBox(dadosretornados("ID_PROD"))
End While
End If
here is the function buscadados
Function buscadadosacess(sql As String)
oConn.ConnectionString = strConn
oConn.Open()
If oConn.State = ConnectionState.Open Then
ACommand = New OleDbCommand(sql, oConn)
'define um dataAdapter
AAdapter = New OleDbDataAdapter()
AAdapter.SelectCommand = ACommand
'define e preenche um DataTable com os dados
ATabela = New DataTable()
AAdapter.Fill(ATabela)
' associar campos a base de dados
xy = ATabela.CreateDataReader
' Ler da tabela
'linha = ACommand.ExecuteReader
End If
'Tipo de dados incorrecto na expressão de critérios.'
Return xy
End Function
thanks guys <3
the error was just a "." in the SQL Setence, here it goes the SQL SENTENCE Correct:
Dim sql As String = "select totais.id_fat,totais.valor_siva,totais.iva,totais.valortotal,totais.data,totais.nome_cliente,fat_prods.id_fat,fat_prods.id_prod,fat_prods.quantidade,fat_prods.preco,fat_prods.id_cliente,fat_prods.descricao from totais INNER JOIN fat_prods ON totais.id_fat=fat_prods.id_fat WHERE totais.id_fat=" + valor.ToString + ""
thanks for all the help

affect the result of sql query to textbox

am using sqlserver 2008 and vb.net
i tried to affect the result of sql query to my textboxs.
here the code that i have tried
Dim rd As SqlDataReader
Try
Cn.Open()
cmd = New SqlCommand("SELECT pk_veh, désignation, projet, version, [taille de lot] from [Cutting software].dbo.vehicule WHERE désignation = '" & Form1.ComboBox3.SelectedValue & "'", Cn)
rd = cmd.ExecuteReader
While rd.Read
imp.TextBox1.Text = rd.GetInt32("pk_veh")
imp.TextBox2.Text = rd.GetString("désignation")
imp.TextBox3.Text = rd.GetString("projet")
imp.TextBox4.Text = rd.GetString("version")
imp.TextBox5.Text = rd.GetInt32("[taille de lot]")
imp.Show()
End While
Cn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
while i checked the type of my columns i always have this error
System.InvalidCastException: 'La conversion de la chaîne "pk_veh" en type 'Integer' n'est pas valide.'FormatException: Input string was not in a correct format.
here the type of my columns
pk_veh,[taille de lot] : int
désignation,projet,version : varchar[50]
here the solution
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rd As SqlDataReader
Try
Cn.Open()
Dim cmd As New SqlCommand("SELECT isnull(pk_veh,0)pk_veh, isnull(designation,'')designation, isnull(projet,'')projet, isnull(version,'')version, isnull(taille_de_lot,0)taille_de_lot from [Cutting software].dbo.vehicule WHERE designation = '" & Form1.ComboBox3.SelectedValue & "'", Cn)
rd = cmd.ExecuteReader
While rd.Read
imp.TextBox1.Text = rd.GetInt32(0)
imp.TextBox2.Text = rd.GetString(1)
imp.TextBox3.Text = rd.GetString(2)
imp.TextBox4.Text = rd.GetString(3)
imp.TextBox5.Text = rd.GetInt32(4)
End While
Cn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
imp.Show()
End Sub

Error displaying data using datareader VB.NET and SQL Server

I'm trying to show the user role once the login success, but, I cannot obtain the behavior that I want. I'm a beginner and here a put my piece of code what I'm using now.
Sub LoginSistema()
Try
AbrirConexion()
Comando = New SqlCommand("select * from tbl_usuarioslogin where username = '" & frmLoginWindow.TextBox1.Text & "' and password = '" & frmLoginWindow.TextBox2.Text & "'")
Comando.CommandType = CommandType.Text
Comando.Connection = Conexion
Lector = Comando.ExecuteReader()
If Lector.HasRows Then
Lector.Read()
If Lector.GetValue(1).ToString = "Victor" Then
MsgBox("Bienvenido :) " + Lector(8).ToString())
CerrarConexion()
Lector.Close()
Else
MsgBox("Error al iniciar sesion en el Sistema.")
CerrarConexion()
Lector.Close()
End If
Else
MsgBox("No hay datos leidos de la base de datos.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
See ya,

VB.Net ignores isDBNull condition

I'm programming a dog adoption form. It retrieves data from a Access DB then the user can adopt up to three dogs, each one of them specified in 3 different fields. I'm doing it this way because I previously tried to do it with arrays, with no luck.
The issue comes here (highlighted in bold):
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
cmd.CommandText = "select adopcion1, adopcion2, adopcion3 from usuarios where codigo_usuario = " & FormPrincipal.codigo_usuario & ""
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader
While dr.Read()
**If dr.IsDBNull(1) Then
posicionAdopcion = 1
ElseIf dr.IsDBNull(2) Then
posicionAdopcion = 2
ElseIf dr.IsDBNull(3) Then
posicionAdopcion = 3
Else
MsgBox("Lo sentimos, solo puedes hacer un máximo de 3 adopciones")
Exit Sub**
End If
End While
dr.Close()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación.")
Me.Close()
End Try
and
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
**If (posicionAdopcion = 1) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION1 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 2) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION2 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 3) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION3 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
End If**
cmd.ExecuteNonQuery()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación...")
Me.Close()
End Try
What I'm trying to do is to check if the adoption fields (adopcion1, adopcion2, adopcion3) are empty, if they are, place the name of the dog there. If they are not, check for the next free slot. If none available, print the corresponding error message. But what the program does is to overwrite the adopcion1 (first field) no matter what.
I have checked this thread, I may be having a similar issue misunderstanding isDBNull usage, but so far I'm trying to do what it's stated there with no result.
What I'm doing wrong?
I got it, as I expected it was a silly mistake: I was retrieving the first data field from 1, and not from 0. Thus skipping it entirely:
If dr.isDBNull(0) Then
posicionAdopcion = 1
But yes, the code seems clunky, didn't know about SQL parameters, going to check them ASAP.
Thanks for the help!

EPPlus in VB.net

I'm trying to fill an existing xls file with EPPlus, but i never use it before. I have to search my data in a DB.
After insert data, the user could save the file on his computer, I doesn't know anything about EPPlus so, i made this :
Dim ExistFile = Server.MapPath("~/Vues/tableau_qualif1.xlsx")
Dim File = New FileInfo(ExistFile)
Dim Connection As New SqlConnection(ConfigurationManager.ConnectionStrings("Formation_2014ConnectionString").ConnectionString)
Dim i = 3
Dim Query = "SELECT * FROM personnes"
Using package As New ExcelPackage(File)
package.Load(New FileStream(ExistFile, FileMode.Open))
Dim workSheet As ExcelWorksheet = package.Workbook.Worksheets("Feuil1")
Try
'Ouverture de la connexion
Connection.Open()
'Définition de la commande et de ses paramètres
Dim Commande As New SqlCommand(Query, Connection)
'Création du SqlDataAdapter et du DataSet (En fonction de la Commande)
Dim Adaptateur As New SqlDataAdapter(Commande)
Dim MonDataSet As New DataSet
Try
'Définition de l'adaptateur
Adaptateur.Fill(MonDataSet, "Personnes")
For Each Ligne As DataRow In MonDataSet.Tables("Personnes").Rows()
workSheet.Cells("A" & i).Value = Ligne("Prenom_personne").ToString() & " " & Ligne("Nom_personne").ToString()
i = i + 1
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
Catch ex As Exception
MsgBox(ex.Message)
End Try
'Fermeture de la connexion
Connection.Close()
package.Save()
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.BinaryWrite(package.GetAsByteArray())
Response.End()
End Using
This code crash at
Response.BinaryWrite(package.GetAsByteArray())
Anyone could help me with this ? Thanks a lot !
My line
package.save()
cause my issues, I just remove this line and all work fine !