NETITC
 


>> Navegação >> Tópico >> SubTópico
NomeTítulo Tópicos
Reginaldo Ribeiro
Dúvida iniciada: 5/31/2007 7:49:02 AM

problemas na criação de menu dinamicos


Dúvida:  Pessoal me ajudem, esse codigo abaixo está funcionando, mais nao do jeito que eu quero.. Desse jeito que o codigo esta mostrando o FrmPrincipal carrega sem antes o usuario digitar a senha, ele carrega com o menu default que vem do banco de dados, nesse menu default tem um menu chamado conectar, quando eu clico em conectar ele exibi todos os menus que esse usuario valido tem acesso. eu quero que a tela de login aparece antes do frmprincipal(meu mdi) com todos os menus que esse usuario tem acesso.

esse site eu usei como pesquisa para fazer esse sistema de menus dinamicos

http://www.microsoft.com/brasil/msdn/Tecnologias/vbnet/visualbasic_MenusDinamicos.mspx

Qualquer duvida estou a disposição para enviar o projeto ou qualquer coisa para me ajudarem a resolver esse meu problema

Veja o codigo fonte



MEU FORM DO LOGIN





Imports System.Data

Imports System.Data.SqlClient

Imports System.Text



Public Class frmLogin

Inherits System.Windows.Forms.Form

'Instância local da classe que armazena o usuário

Private usrUsuario As New clsUsuario

'Instância local do objeto de conexão

Private conDB As New SqlConnection



#Region " Windows Form Designer generated code "



Public Sub New()

MyBase.New()



'This call is required by the Windows Form Designer.

InitializeComponent()



'Add any initialization after the InitializeComponent() call



End Sub



Public Sub New(ByRef pUsuario As clsUsuario, ByVal pconBD As System.Data.SqlClient.SqlConnection)

'Chamo o construtor da classe base para que as

'rotinas básicas sejam executadas

Me.New()

usrUsuario = pUsuario

conDB = pconBD

End Sub



'Form overrides dispose to clean up the component list.

Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose()

End If

End If

MyBase.Dispose(disposing)

End Sub



'Required by the Windows Form Designer

Private components As System.ComponentModel.IContainer



'NOTE: The following procedure is required by the Windows Form Designer

'It can be modified using the Windows Form Designer.

'Do not modify it using the code editor.

Friend WithEvents Label1 As System.Windows.Forms.Label

Friend WithEvents txtUsuario As System.Windows.Forms.TextBox

Friend WithEvents Label2 As System.Windows.Forms.Label

Friend WithEvents btnOK As System.Windows.Forms.Button

Friend WithEvents btnCancelar As System.Windows.Forms.Button

Friend WithEvents txtSenha As System.Windows.Forms.TextBox

Friend WithEvents Panel1 As System.Windows.Forms.Panel

Friend WithEvents Label4 As System.Windows.Forms.Label

Private Sub InitializeComponent()

Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmLogin))

Me.Label1 = New System.Windows.Forms.Label

Me.txtUsuario = New System.Windows.Forms.TextBox

Me.Label2 = New System.Windows.Forms.Label

Me.txtSenha = New System.Windows.Forms.TextBox

Me.btnOK = New System.Windows.Forms.Button

Me.btnCancelar = New System.Windows.Forms.Button

Me.Panel1 = New System.Windows.Forms.Panel

Me.Label4 = New System.Windows.Forms.Label

Me.SuspendLayout()

'

'Label1

'

Me.Label1.AutoSize = True

Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

Me.Label1.ForeColor = System.Drawing.Color.FromArgb(CType(0, Byte), CType(0, Byte), CType(192, Byte))

Me.Label1.Location = New System.Drawing.Point(12, 56)

Me.Label1.Name = "Label1"

Me.Label1.Size = New System.Drawing.Size(51, 18)

Me.Label1.TabIndex = 0

Me.Label1.Text = "Usuário"

'

'txtUsuario

'

Me.txtUsuario.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

Me.txtUsuario.ForeColor = System.Drawing.Color.FromArgb(CType(0, Byte), CType(0, Byte), CType(192, Byte))

Me.txtUsuario.Location = New System.Drawing.Point(12, 72)

Me.txtUsuario.MaxLength = 15

Me.txtUsuario.Name = "txtUsuario"

Me.txtUsuario.Size = New System.Drawing.Size(192, 22)

Me.txtUsuario.TabIndex = 1

Me.txtUsuario.Text = ""

'

'Label2

'

Me.Label2.AutoSize = True

Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

Me.Label2.ForeColor = System.Drawing.Color.FromArgb(CType(0, Byte), CType(0, Byte), CType(192, Byte))

Me.Label2.Location = New System.Drawing.Point(12, 103)

Me.Label2.Name = "Label2"

Me.Label2.Size = New System.Drawing.Size(44, 18)

Me.Label2.TabIndex = 2

Me.Label2.Text = "Senha"

'

'txtSenha

'

Me.txtSenha.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

Me.txtSenha.ForeColor = System.Drawing.Color.FromArgb(CType(0, Byte), CType(0, Byte), CType(192, Byte))

Me.txtSenha.Location = New System.Drawing.Point(12, 119)

Me.txtSenha.MaxLength = 15

Me.txtSenha.Name = "txtSenha"

Me.txtSenha.PasswordChar = Microsoft.VisualBasic.ChrW(42)

Me.txtSenha.Size = New System.Drawing.Size(192, 22)

Me.txtSenha.TabIndex = 3

Me.txtSenha.Text = ""

'

'btnOK

'

Me.btnOK.Location = New System.Drawing.Point(232, 72)

Me.btnOK.Name = "btnOK"

Me.btnOK.Size = New System.Drawing.Size(76, 24)

Me.btnOK.TabIndex = 4

Me.btnOK.Text = "&Ok"

'

'btnCancelar

'

Me.btnCancelar.DialogResult = System.Windows.Forms.DialogResult.Cancel

Me.btnCancelar.Location = New System.Drawing.Point(232, 119)

Me.btnCancelar.Name = "btnCancelar"

Me.btnCancelar.Size = New System.Drawing.Size(76, 24)

Me.btnCancelar.TabIndex = 5

Me.btnCancelar.Text = "&Cancelar"

'

'Panel1

'

Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D

Me.Panel1.Location = New System.Drawing.Point(12, 34)

Me.Panel1.Name = "Panel1"

Me.Panel1.Size = New System.Drawing.Size(296, 8)

Me.Panel1.TabIndex = 6

'

'Label4

'

Me.Label4.AutoSize = True

Me.Label4.Font = New System.Drawing.Font("Arial", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

Me.Label4.ForeColor = System.Drawing.Color.Coral

Me.Label4.Location = New System.Drawing.Point(12, 6)

Me.Label4.Name = "Label4"

Me.Label4.Size = New System.Drawing.Size(66, 28)

Me.Label4.TabIndex = 8

Me.Label4.Text = "Login"

'

'frmLogin

'

Me.AcceptButton = Me.btnOK

Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)

Me.CancelButton = Me.btnCancelar

Me.ClientSize = New System.Drawing.Size(322, 156)

Me.Controls.Add(Me.Label4)

Me.Controls.Add(Me.Panel1)

Me.Controls.Add(Me.btnCancelar)

Me.Controls.Add(Me.btnOK)

Me.Controls.Add(Me.txtSenha)

Me.Controls.Add(Me.Label2)

Me.Controls.Add(Me.txtUsuario)

Me.Controls.Add(Me.Label1)

Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog

Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)

Me.Name = "frmLogin"

Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent

Me.Text = "Login"

Me.ResumeLayout(False)



End Sub



#End Region



Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click

Try

If UsuarioValido(txtUsuario.Text, txtSenha.Text) Then

Me.Close()

'frmPrincipal.Show()

Else

MessageBox.Show("Usuário/senha inválidos.", "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Information)

txtUsuario.Focus()

End If

Catch ex As Exception

MessageBox.Show(ex.Message.ToString, "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

End Sub



Private Function UsuarioValido(ByVal pstrUsuario As String, ByVal pstrSenha As String) As Boolean

Dim olecmdCommand As SqlCommand

Dim olerdrReader As SqlDataReader

Dim strQuery As New StringBuilder

Dim bolResult As Boolean



Try

conDB.ConnectionString = "server=localhost\SQLEXPRESS;Initial Catalog=Hunter;User Id=hunter;Password=123456;"

conDB.Open()

strQuery.Append("select login, grupoid from usuario ")

strQuery.Append("where login = '" & txtUsuario.Text.ToUpper() & "' ")

strQuery.Append("and senha = '" & txtSenha.Text.ToUpper() & "' ")

olecmdCommand = New System.Data.SqlClient.SqlCommand(strQuery.ToString(), conDB)

olerdrReader = olecmdCommand.ExecuteReader()



If olerdrReader.Read() Then

usrUsuario.Nome = olerdrReader.Item("login")

usrUsuario.Grupo = olerdrReader.Item("grupoid")

bolResult = True

End If

Catch ex As Exception

Throw New Exception("Ocorreu um erro ao autenticar o usuário: " & ex.Message)

bolResult = False

Finally

conDB.Close()

End Try



Return bolResult

End Function



Private Sub txtUsuario_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtUsuario.GotFocus

txtUsuario.Select(0, txtUsuario.Text.Length())

End Sub



Private Sub txtSenha_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSenha.GotFocus

txtSenha.Select(0, txtSenha.Text.Length())

End Sub



Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click

Me.Close()

End Sub



Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'MessageBox.Show("Para testar o programa, utilize os usuários: Roberto ou Alberto e senhas Rob ou Alb (respectivamente)", "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Information)

End Sub

End Class



MEU FORM PRINCIPAL (MDI)



Imports System.Data

Imports System.Data.sqlclient



Public Class frmPrincipal

Inherits System.Windows.Forms.Form



#Region " Windows Form Designer generated code "



Public Sub New()

MyBase.New()



'This call is required by the Windows Form Designer.

InitializeComponent()



'Add any initialization after the InitializeComponent() call



End Sub



'Form overrides dispose to clean up the component list.

Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose()

End If

End If

MyBase.Dispose(disposing)

End Sub



'Required by the Windows Form Designer

Private components As System.ComponentModel.IContainer



'NOTE: The following procedure is required by the Windows Form Designer

'It can be modified using the Windows Form Designer.

'Do not modify it using the code editor.

Private Sub InitializeComponent()

Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmPrincipal))

Me.SuspendLayout()

'

'frmPrincipal

'

Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)

Me.ClientSize = New System.Drawing.Size(687, 328)

Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)

Me.IsMdiContainer = True

Me.Name = "frmPrincipal"

Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen

Me.Text = "Form Principal"

Me.ResumeLayout(False)



End Sub



#End Region

'Instância do objeto onde o menu será montado

Private mmnMenuPrincipal As New MainMenu

'Instância da classe que manipula os menus

Private mndMenuD As New clsMenuDinamico

'Instância da classe que armazena o usuário

Private usrUsuario As New clsUsuario

'Instância do objeto de conexão

Private conDB As New sqlconnection



Private Sub frmPrincipal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _

Handles MyBase.Load

'Conectar(sender, e)

'Atribui atributo ao menu do form

Me.Menu = mmnMenuPrincipal

conDB.ConnectionString = "server=localhost\SQLEXPRESS;Initial Catalog=Hunter;User Id=hunter;Password=123456;"



'Monta o menu default (nenhum usuário autenticado)

Try

mndMenuD.MontaMenu(0, mmnMenuPrincipal, conDB, AddressOf EventoMenu_Click)

Catch ex As Exception

MessageBox.Show("Ocorreu um erro durante a criação dos menus: " & ex.Message, "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

End Sub



Private Sub EventoMenu_Click(ByVal sender As Object, ByVal e As System.EventArgs)

'Apresento o item clicado e, após o casting,

'obtenho a propriedade Text do objeto

Select Case CType(sender, MenuItem).Text

Case "&Conectar"

Conectar(sender, e)

Case "&Desconectar"

'Executa o método MontaMenu p/ o menu Default

Try

mndMenuD.MontaMenu(0, mmnMenuPrincipal, conDB, AddressOf EventoMenu_Click)

Catch ex As Exception

MessageBox.Show("Ocorreu um erro durante a criação dos menus: " & ex.Message, "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

Case "Sai&r"

Me.Close()

Case Else

MessageBox.Show("Menu """ & CType(sender, MenuItem).Text & """ selecionado.", "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Select



'� possível manipular os atributos do menu através

'do método RetornaMenu (collection)

'Ex: mndMenuD.RetornaMenu("Form1").Enabled = False

'Não esqueça do Try...Catch

End Sub



Private Sub Conectar(ByVal sender As Object, ByVal e As System.EventArgs)

'Variável para formulário de login

Dim frm As frmLogin

Dim usrUsuarioLogin As New clsUsuario



'Nova instância do form de login, usando construtor customizado, passando a

'instância da classe usuário e instância do objeto conexâo no BD

frm = New frmLogin(usrUsuarioLogin, conDB)

'Carregar form no modo modal

frm.ShowDialog(Me)



'Se um usuário foi autenticado, montar menu

If Not usrUsuarioLogin.Nome Is Nothing Then

mndMenuD.MontaMenu(usrUsuarioLogin.Grupo, mmnMenuPrincipal, conDB, AddressOf EventoMenu_Click)

End If

End Sub

End Class





Minha Classe CLSUSUARIO



Public Class clsUsuario

Private strNome As String

Private shtGrupo As Short

Public Property Nome() As String

Get

Return strNome

End Get

Set(ByVal Value As String)

strNome = Value

End Set

End Property



Public Property Grupo() As Integer

Get

Return shtGrupo

End Get

Set(ByVal Value As Integer)

shtGrupo = Value

End Set

End Property

End Class





CLASSE CLSMENUDINAMICO



Imports System.Data

Imports System.Data.SqlClient

Imports System.Text



Public Class clsMenuDinamico

'Collection utilizada para armazenar os itens de menu

Private arlMenus As New ArrayList



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''' Método utilizado para adicionar Menu nível zero ou sub-item

Public Sub AdicionarItem(ByVal pPai As Object, ByVal pMenuCaption As String, _

Optional ByRef pEventHandler As Object = Nothing)

'Um novo item é criado com o caption informado

Dim mniMenuItem As New MenuItem(pMenuCaption)



'Se for um item principal (MainMenu), incluir um

'item principal (nível zero)

If TypeOf pPai Is MainMenu Then

'Se o item já existir, dispara exception

If Not RetornaMenu(pMenuCaption) Is Nothing Then

Throw New Exception("Item de menu (" & pMenuCaption & ") já existe")

End If

'Adiciona o item criado à instância de MainMenu

'(recebido como parâmetro)

pPai.MenuItems.Add(mniMenuItem)

Else

RetornaMenu(pPai).MenuItems.Add(mniMenuItem)

End If



'Adiciona o item à collection

arlMenus.Add(mniMenuItem)



'Adiciona Handler para o evento Click (apenas se informado)

If Not pEventHandler Is Nothing Then

AddHandler mniMenuItem.Click, pEventHandler

End If

End Sub



''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''' RetornaMenu - Retorna o item de menu do caption informado

Public Function RetornaMenu(ByVal pCaption As String) As MenuItem

Dim arlTemp As MenuItem



For Each arlTemp In arlMenus

'Verifica se é o item informado

If arlTemp.Text = pCaption Then

'Se for, retorna o item do menu

Return arlTemp

End If

Next

Return Nothing

End Function



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''' MontaMenu - Cria o menu no formulário correspondente

Public Sub MontaMenu(ByVal pGrupo As Integer, _

ByRef pMenuPrincipal As MainMenu, _

ByRef pconDB As SqlConnection, _

ByVal pEventHandler As EventHandler)

Dim olecmdCommand As New SqlCommand

Dim olerdrReader As SqlDataReader

Dim strQuery As New StringBuilder



'Apaga o conteúdo da collection atual o menu existente

arlMenus.Clear()

pMenuPrincipal.MenuItems.Clear()



'Pesquisa todos os itens para o grupo informado

Try

With strQuery

.Append("SELECT a.colunaid, a.ParentID, a.Nivel, a.Descricao, ")

.Append("(select descricao from menu where menuid = a.parentid ) ")

.Append("as ParentDescricao ")

.Append("FROM Menu AS a, Grupo AS b, MenuGrupo AS c ")

.Append("WHERE a.MenuID=c.menuid and ")

.Append("b.GrupoID=c.grupoid and ")

.Append("b.GrupoID = " & pGrupo & " ")

.Append("ORDER BY a.colunaid, a.ParentID, a.Nivel, a.SubOrdem;")

End With

pconDB.Open()

olecmdCommand = New SqlCommand(strQuery.ToString(), pconDB)

olerdrReader = olecmdCommand.ExecuteReader()



'Para cada item retornado, adicionar item no menu.

While olerdrReader.Read()



'Se item nível zero (Arquivo, Editar, Help,

'etc), primeiro parâmetro é o MainMenu

If olerdrReader.Item("Nivel") = 0 Then

AdicionarItem(pMenuPrincipal, olerdrReader.Item("Descricao"))

Else

'Se sub-item, primeiro parâmetro é o caption

'do Item nível zero, isto é, pai do sub-item

AdicionarItem(olerdrReader.Item("ParentDescricao"), _

olerdrReader.Item("Descricao"), pEventHandler)

End If

End While

Catch ex As Exception

MessageBox.Show("Ocorreu um erro ao montar os menus: " & ex.Message, "Menu Dinamico", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

pconDB.Close()

End Sub

End Class



Respostas Data Resposta: 5/31/2007 7:49:02 AM
Mauricio Junior Reginaldo,

Este sistema é windows form? Ou WebForm?
Estou disposto a ajudar.

Heroes


Vídeos

 
Curso de C#


Visto por 41 pessoas.

Vídeo: Gerando Hash com .NET


Visto por 907 pessoas.

Criptografia para ser usada na URL


Visto por 1234 pessoas.

Mudar o toque do iPhone


Visto por 1779 pessoas.

12345678