效果如图所示,

1.给最后一列后加按钮

 private void FrmUserManagement_Load(object sender, EventArgs e)
 {
     // 获取用户信息
     LoadData();

     // 获取最后一列的索引
     int lastIndex = dataGridView1.Columns.Count; 

     // 创建一个新的Button列
     DataGridViewButtonColumn btnColumn = new()
     {
         HeaderText = "操作",
         Text = "分配权限",
         Name = "AuthorityMgt", // 设置列名称
         UseColumnTextForButtonValue = true // 使用列头文本作为按钮显示的文本
     };
     // 将按钮列添加到dataGridView1的最后一列
     dataGridView1.Columns.Insert(lastIndex, btnColumn); 
}

2.根据不同身份实现不同的按钮功能,绑定cellFormatting事件可根据身份修改按钮显示的文字

 // 绑定 CellFormatting 事件以根据 role 列值更改按钮文本
 dataGridView1.CellFormatting += DataGridView_CellFormatting!;


 // 为按钮添加点击事件
 dataGridView1.CellClick += (s, args) =>
 {
     if (args.ColumnIndex == dataGridView1.Columns["AuthorityMgt"].Index && args.RowIndex >= 0)
     {
         if (dataGridView1.Rows[args.RowIndex].Cells["AuthorityMgt"] is DataGridViewButtonCell cell && cell.Value.ToString() == "分配权限")
         {
             // 分配权限
             AuthorityMgt(args.RowIndex);
         }
     }
 };

3.根据 role 列值更改按钮文本

 /// <summary>
 /// 根据 role 列值更改按钮文本
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
 {
     // 检查是否操作的是"AuthorityMgt"列,并且行索引有效
     if (e.ColumnIndex == dataGridView1.Columns["AuthorityMgt"].Index &&
         e.RowIndex >= 0 &&
         dataGridView1.Rows[e.RowIndex].Cells["role"] is not null)
     {
         // 获取当前行"role"列的值并转换为字符串
         string userRole = dataGridView1.Rows[e.RowIndex].Cells["role"].Value?.ToString()!;

         if (!string.IsNullOrEmpty(userRole))
         {
             if (userRole=="管理员")
             {
                 e.Value = "撤回权限";
             }
             else if(userRole=="普通用户")
             {
                 e.Value = "分配权限";
             }
         }
     }
 }

4.最后是按钮的点击事件,修改权限

/// <summary>
/// 修改权限
/// </summary>
/// <param name="rowIndex"></param>
private void AuthorityMgt(int rowIndex)
{
    // 获取对应行的数据,然后进行分配权限的操作
    var row = dataGridView1.Rows[rowIndex];
    var userId = row.Cells["db_id"].Value; // "UserId"是t_user表中的用户ID字段
    string currentRole = row.Cells["role"].Value.ToString()!;
    // 根据当前角色执行相应的SQL更新操作
    string updateSql;
    if (currentRole == "普通用户")
    {
        updateSql= $"update t_user set role='管理员' where db_id={userId}";
    }
    else
    {
        updateSql = $"update t_user set role='普通用户' where db_id={userId}";
    }
    // 根据用户Id分配权限
    int res = _helper.ExecuteNonQuery(updateSql);
    if (res > 0)
    {
        MessageBox.Show("权限更改成功");
        LoadData();
    }
}

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐