TIPOS DE VARIAVEIS
TIPOS DE VARIAVEIS
O codigo converte os valores recebidos da text box de string para integer e depois converte para char ( tabelaASCII)
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer >>> DEFININDO A VARIAVEL
valor = TextBox1.Text
Dim valor_convertido As Char
valor_convertido = Chr(valor)
MsgBox(valor_convertido)
Label1.Text = ("voce digitou o valor " + valor_convertido)
End Sub
End Class
OUTRO EXEMPLO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim Lista As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer
valor = TextBox1.Text
Dim valor_convertido As Char
valor_convertido = Chr(valor)
' vbCrLf eh quebra de linha
Lista = ("O numero " + valor.ToString + "eh " + valor_convertido.ToString)
TextBox2.Text = TextBox2.Text + Lista + vbCrLf
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim Lista As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer = Int(TextBox1.Text)
If (valor = 10) Then
MsgBox("the number typed was 10 ")
Else
MsgBox("the number typed was NOT 10 ")
If (valor = 20) Then
MsgBox("the number typed was 20 ")
Else
MsgBox("the number typed was NOT 20")
End If
End If
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim Lista As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer = Int(TextBox1.Text)
If (valor = 10) Then
Dim NOME As String >>>>>>>>>>>> a var só vale dentro do bloco do if ou seja nao eh acessada externamente
MsgBox("the number typed was 10 ")
Else
MsgBox("the number typed was NOT 10 ")
If (valor = 20) Then
MsgBox("the number typed was 20 ")
Else
MsgBox("the number typed was NOT 20")
End If
End If
End Sub
End Class
Checkbox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer = Int(TextBox1.Text)
Dim caixa_marcacao As String
'testa se a caixa foi marcada e se sim atribui a var
'forecolor muda a cor da fonte
If CheckBox1.Checked Then
caixa_marcacao = "S"
MsgBox(caixa_marcacao)
Label2.ForeColor = Color.Red
Else
caixa_marcacao = "N"
MsgBox(caixa_marcacao)
End If
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer = Int(TextBox1.Text)
Dim caixa_marcacao As String
Dim contador As Integer = 1
While contador <= valor
MsgBox(contador)
contador += 1
End While
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim valor As Integer = Int(TextBox1.Text)
Dim caixa_marcacao As String
Dim contador As Integer = 1
While contador <= valor
MsgBox(contador)
contador += 1
End While
For i As Integer = 1 To valor
TextBox2.Text = TextBox2.Text + "o indice eh " + i.ToString + vbCrLf
if i = 10 then
exit_for (isso faz sair do for por uma condição )
end if
Next
REDIRECIONAR JANELAS
para que um projeto veja o outro ele precisa ser adicionado nas referencias e depois é criado como uma variavel instanciada
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim f As New janela_2.Form_janela2
f.ShowDialog()
End Sub
End Class
A classe é um arquivo .vb onde épublicado via public a classe
Public Class ContaCorrente
Public Titular As String = "Ronaldo"
Public Agencia As Integer = 1000
Public Conta As Integer = 100 - 8
Public Saldo As Double = 12.0
End Class
Apos criada deve ser instanciada
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ContaLucas As New ContaCorrente
ContaLucas.Titular = "Lucas Fontini"
ContaLucas.Saldo = 12.5
ContaLucas.Conta = 100
ContaLucas.Agencia = 1455
MsgBox(ContaLucas.Titular)
MsgBox(ContaLucas.Saldo)
MsgBox(ContaLucas.Conta)
Public Class ContaCorrente
Public Titular As String = "Ronaldo"
Public Agencia As Integer = 1000
Public Conta As Integer = 100 - 8
Public Saldo As Double = 12.0
Public Function Sacar(valor As Double) As Boolean >> esse eh o retorno boleano
Dim Retorno As Boolean
If Saldo >= valor Then
Retorno = False
MsgBox("menor")
Else
Retorno = True
MsgBox("maior")
End If
Return Retorno aqui retorna o valor
End Function
End Class
chamar no form principal
Private Sub Button_FUNC_Click(sender As Object, e As EventArgs) Handles Button_FUNC.Click
Dim ContaLucas As New ContaCorrente
ContaLucas.Titular = "Lucas Fontini"
ContaLucas.Saldo = 12.5
ContaLucas.Conta = 100
ContaLucas.Agencia = 1455
Dim saque As Double = Val(TextBox1.Text)
Dim retorno As Boolean = ContaLucas.Sacar(saque) >>> aqui chama a função
MsgBox(retorno)
é POSSIVEL DEIXAR UMA CLASSE DENTRO DESSE NAME SPACE E UTILIZAR CONFORME A NECESSIDADE
Namespace MeuNamespace
Public Class MinhaClasse
Public Sub MeuMetodo()
Console.WriteLine("Olá do MeuNamespace!")
End Sub
End Class
End Namespace
Module Program
Sub Main(args As String())
Dim minhaInstancia As New MeuNamespace.MinhaClasse()
minhaInstancia.MeuMetodo()
End Sub
End Module
Public Class MinhaClasse
Private ReadOnly meuCampo As Integer
Public Sub New(valorInicial As Integer)
meuCampo = valorInicial
End Sub
Public Sub ExibirValor()
Console.WriteLine("Valor do campo: " & meuCampo)
End Sub
End Class
Module Program
Sub Main(args As String())
Dim minhaInstancia As New MinhaClasse(10)
minhaInstancia.ExibirValor()
End Sub
End Module
Public Class MinhaClasse
Private _minhaPropriedade As String
Public Property MinhaPropriedade As String
Get
Return _minhaPropriedade
End Get
Set(value As String)
_minhaPropriedade = value
End Set
End Property
End Class
Dim objeto As New MinhaClasse()
objeto.MinhaPropriedade = "Hello, world!" ' Atribui um valor à propriedade
Console.WriteLine(objeto.MinhaPropriedade) ' Obtém o valor da propriedade e o exibe no console
Metodos
Public Sub CalcularSoma(ByVal a As Integer, ByVal b As Integer)
Dim soma As Integer = a + b
Console.WriteLine("A soma de {0} e {1} é: {2}", a, b, soma)
End Sub
GET E SET PROPERTY
Public Class Colaborador
Public Property Funcionario As Pessoa
Public Property Salario As Double
Private m_BancoHoras As Double
Public Property BancoHoras As Double
Get
Return m_BancoHoras
End Get
Set(value As Double)
If value >= 0 Then
m_BancoHoras = value
Else
m_BancoHoras = 0
End If
End Set
End Property
End Class
CONSTRUTOR - MESMA COISA DO PYTHON
Public Class Colaborador
Public Property Funcionario As Pessoa
Public Property Salario As Double
Private m_BancoHoras As Double
DEFINE COMO PUBLICO E QUANDO FOR INSTANCIAR PASSA OS PARAMETROS
Public Sub New(_Pessoa As Pessoa, _Salario As Double, _BancoHoras As Double)
Funcionario = _Pessoa
Salario = _Salario
BancoHoras = _BancoHoras
End Sub
Property BancoHoras As Double
Get
Return m_BancoHoras
End Get
Set(value As Double)
If value >= 0 Then
m_BancoHoras = value
Else
m_BancoHoras = 0
End If
End Set
End Property
End Class
Public Class Colaborador
Public Funcionario As Pessoa
Public Salario As Double
Private m_BancoHoras As Double
Shared m_Contador As Integer
Public Sub New(_Pessoa As Pessoa, _Salario As Double, _BancoHoras As Double)
Funcionario = _Pessoa
Salario = _Salario
BancoHoras = _BancoHoras
m_Contador += 1
End Sub
Shared ReadOnly Property Contador As Integer
Get
Return m_Contador
End Get
End Property
Property BancoHoras As Double
Get
Return m_BancoHoras
End Get
Set(value As Double)
If value >= 0 Then
m_BancoHoras = value
Else
m_BancoHoras = 0
End If
End Set
End Property
End Class
Dim inputString As String = "Hello, world!"
Dim startIndex As Integer = 7 ' Índice baseado em zero da posição inicial da substring
Dim length As Integer = 5 ' Comprimento da substring a ser extraída
Dim substring As String = inputString.Substring(startIndex, length)
Console.WriteLine(substring)
Certamente! Aqui está um exemplo de como usar a função Substring no VB.NET para extrair uma parte de uma string:
vb
Copy code
Dim inputString As String = "Hello, world!" Dim startIndex As Integer = 7 ' Índice baseado em zero da posição inicial da substring Dim length As Integer = 5 ' Comprimento da substring a ser extraída Dim substring As String = inputString.Substring(startIndex, length) Console.WriteLine(substring)
Neste exemplo, temos a string "Hello, world!" e queremos extrair a substring "world". Definimos startIndex como 7 para indicar que queremos começar a partir do índice 7 (que corresponde ao caractere "w" na string) e definimos length como 5 para indicar que queremos extrair 5 caracteres a partir do índice 7.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim entrada As String = TextBox1.Text
Dim Nome As String
Dim Sobrenome As String
Dim posicao As Integer
Dim startIndex As Integer = 0
'pega o indice do caracter escolhido no caso o espaco
posicao = InStr(entrada, " ")
'mostra do indice ate o final da string
'entrada lucas fontini
Sobrenome = entrada.Substring(posicao)
'fontini
Nome = entrada.Substring(startIndex, posicao)
'lucas
MsgBox(Nome)
Private Sub Btn_Principal2_Click(sender As Object, e As EventArgs) Handles Btn_Principal2.Click
Try
ExecutaTesteURL2()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Sub ExecutaTesteURL2()
Dim url As String = Txt_Url.Text
If url = "" Then
Throw New Exception("URL vazia")
End If
Dim separador As String = Txt_Separador.Text
If separador = "" Then
Throw New Exception("Separador vazio")
End If
Dim posicaoInterrogacao As Integer
posicaoInterrogacao = url.IndexOf(separador)
If posicaoInterrogacao = -1 Then
Throw New Exception("Posição vazia")
End If
url = url.Substring(posicaoInterrogacao + 1)
MsgBox(url)
End Sub
REG EXP
Private Sub Btn_Principal3_Click(sender As Object, e As EventArgs) Handles Btn_Principal3.Click
Dim vFrase As String = "O telefone é 23344332"
'Dim vExpressaoRegular As String = "[0123456789][0123456789][0123456789][0123456789][-][0123456789][0123456789][0123456789][0123456789]"
'Dim vExpressaoRegular As String = "[0-9][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9]"
'Dim vExpressaoRegular As String = "[0-9]{5}[-][0-9]{4}"
'Dim vExpressaoRegular As String = "[0-9]{4,5}[-][0-9]{4}"
'Dim vExpressaoRegular As String = "[0-9]{4,5}[-]?[0-9]{4}"
Dim vExpressaoRegular As String = "[0-9]{4,5}-?[0-9]{4}"
// RETORNA FALSE OR TRUE
Dim X As Boolean = Regex.IsMatch(vFrase, vExpressaoRegular)
MsgBox(X)
// RETORNA O VALOR QUE DEU MATCH
Dim Y As Match = Regex.Match(vFrase, vExpressaoRegular)
MsgBox(Y.Value)
End Sub
SUB é uma rotina ou seja uma função que nao retorna valor
Private Sub Btn_Principal_Click(sender As Object, e As EventArgs)
Handles Btn_Principal.Click
// criando um array Idade, deve se definir o tamanho previo que ele vai ter e depois inserindo os valores para cada indice
Dim Idade(3) As Integer
Idade(0) = 30
Idade(1) = 30
Idade(2) = 20
Idade(3) = 25
Dim vPosicoes As Integer = Idade.Length
Dim media As Double = 0
For i As Integer = 0 To vPosicoes - 1
media += Idade(i)
Next
media = media / vPosicoes
Dim Idade2(3) As Integer
Idade2(0) = 30
Idade2(1) = 30
Idade2(2) = 20
Idade2(3) = 25
Dim vPosicoes2 As Integer = Idade.Length
Dim vSomaArray As Integer = Idade2.Sum
Dim media2 As Double = vSomaArray / vPosicoes2
Dim Idade3(3) As Integer
Idade3(0) = 30
Idade3(1) = 30
Idade3(2) = 20
Idade3(3) = 25
Dim media3 As Double = Idade3.Average
Dim vFirst As Integer = Idade3.First
Dim vLast As Integer = Idade3.Last
Dim vMax As Integer = Idade3.Max
Dim vMin As Integer = Idade3.Min
MsgBox(media)
MsgBox(media2)
MsgBox(media3)
End Sub
ARRAY DINAMICO
Private Sub Btn_Principal2_Click(sender As Object, e As EventArgs)
Handles Btn_Principal2.Click
Dim Contas() As ContaCorrente
Contas = {
New ContaCorrente(111, 11111),
New ContaCorrente(222, 22222),
New ContaCorrente(333, 33333),
New ContaCorrente(444, 4444)
}
For i As Integer = 0 To Contas.Length - 1
Dim ContaAtual As ContaCorrente = Contas(i)
Dim vNumero As Integer = ContaAtual.numero
MsgBox(vNumero)
Next
Contas = {
New ContaCorrente(111, 11111),
New ContaCorrente(222, 22222),
New ContaCorrente(333, 33333),
New ContaCorrente(444, 4444),
New ContaCorrente(555, 55555)
}
For i As Integer = 0 To Contas.Length - 1
Dim ContaAtual As ContaCorrente = Contas(i)
Dim vNumero As Integer = ContaAtual.numero
MsgBox(vNumero)
Next
End Sub
LISTAS
Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
' Criando uma lista vazia de números inteiros
Dim numeros As New List(Of Integer)()
' Adicionando elementos à lista
numeros.Add(10)
numeros.Add(20)
numeros.Add(30)
' Acessando elementos da lista
Console.WriteLine("Primeiro elemento: " & numeros(0))
Console.WriteLine("Segundo elemento: " & numeros(1))
Console.WriteLine("Terceiro elemento: " & numeros(2))
' Iterando sobre a lista
Console.WriteLine("Iterando sobre a lista:")
For Each numero As Integer In numeros
Console.WriteLine(numero)
Next
' Removendo um elemento da lista
numeros.Remove(20)
' Verificando se um elemento está presente na lista
Console.WriteLine("O número 20 está na lista? " & numeros.Contains(20))
' Limpando a lista
numeros.Clear()
' Verificando se a lista está vazia
Console.WriteLine("A lista está vazia? " & (numeros.Count = 0))
End Sub
End Module
https://ribeirodti.files.wordpress.com/2010/06/apostila-de-vb-net.pdf