You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中按用户身份隐藏DataGridView列及调试退出问题解决

解决方案

一、根据用户名控制DataGridView列显示

要实现按用户名隐藏列,需先将登录用户名传递到Form2,再根据用户名设置列可见性:

  1. 在Form2中添加公共属性存储用户名
    打开Form2的代码文件,添加以下公共变量:
Public CurrentUserName As String
  1. 修改Form1的登录代码,传递用户名到Form2
    在登录成功后的Form2初始化代码中,增加用户名赋值:
' 原Form1登录成功部分修改后
If scmd.ExecuteScalar().ToString() = "1" Then
    Dim grantedPath = Path.Combine(Application.StartupPath, "granted.jpg")
    PictureBox1.Image = New Bitmap(grantedPath)
    MessageBox.Show("YOU ARE GRANTED WITH ACCESS")
    With Form2
        .lblEmployeeName.Text = "Welcome, " & txt_UserName.Text
        .CurrentUserName = txt_UserName.Text ' 新增:传递当前登录用户名
        .Show()
    End With
    Me.Visible = False
End If
  1. 在Form2中添加列可见性判断逻辑
    在Form2_Load事件的最后,添加根据用户名设置列显示的代码:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        dt = New DataTable
        Dim query = "select INVONO,QTY,VALUEINV from Sales"
        Using adapter As New OleDbDataAdapter(query, cn.ToString)
            adapter.Fill(dt)
        End Using
        Me.DataGridView1.DataSource = dt
        Me.DataGridView1.Refresh()

        ' 新增:根据用户名控制列显示
        Select Case CurrentUserName
            Case "Admin"
                DataGridView1.Columns("VALUEINV").Visible = False
            Case "Owner"
                DataGridView1.Columns("QTY").Visible = False
            Case "User"
                ' 确保所有列都显示
                DataGridView1.Columns("INVONO").Visible = True
                DataGridView1.Columns("QTY").Visible = True
                DataGridView1.Columns("VALUEINV").Visible = True
        End Select
    Catch myerror As OleDbException
        MessageBox.Show("Error: " & myerror.Message)
    Finally
    End Try
End Sub

二、解决关闭Form2后调试进程未停止的问题

问题原因是Form1仅设置为隐藏(Me.Visible = False),并未关闭,导致应用主进程仍在运行。可通过以下两种方式解决:

方法一:在Form2关闭时退出整个应用

在Form2中添加FormClosed事件处理:

Private Sub Form2_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    Application.Exit() ' 终止整个应用进程
End Sub

方法二:以模态方式打开Form2并关闭Form1

修改Form1中打开Form2的代码,使用ShowDialog()(模态对话框),并在对话框关闭后关闭Form1:

' Form1登录成功部分修改
With Form2
    .lblEmployeeName.Text = "Welcome, " & txt_UserName.Text
    .CurrentUserName = txt_UserName.Text
    .ShowDialog() ' 模态打开Form2
End With
Me.Close() ' 关闭Form1,触发应用进程终止

内容的提问来源于stack exchange,提问作者roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:22:40