博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#遍历菜单并设置权限

Posted on 2010-11-22 21:13  我的风之子  阅读(3535)  评论(0编辑  收藏  举报

转载自 http://hi.baidu.com/grounder/blog/item/ad0755ca7121d815bf09e624.html

 

一、加入数据
1、创建数据表
create table t_GroupFormsAuthority(
--FGfaID numeric(6,0) identity primary key ,
FUGroupNo varchar(50) not null ,
FSFormNo
varchar(100) not null ,--系统窗口、报表代码
FGfaIsOk char(1) default '1' ,
FStatus
char(1) default '1',---
FFlag char(1) default '1',---
FCreateDate datetime default getdate() ,
FCreator
varchar(20) null ,
FModifyDate
datetime default getdate() ,
FModifier
varchar(20) null ,
FMemo
text null ,
constraint PK_t_GroupFormsAuthority primary key(FUGroupNo,FSFormNo)
)
go
2、插入数据
Admin MenuItemBase 1 1
Admin MenuItemBase_01
1 1
Admin MenuItemFile
1 1
Admin MenuItemFile_Exit
1 1
Admin MenuItemFile_Print
1 1
Admin MenuItemHelp
1 1
Admin MenuItemWindow
1 1

 

二、新建项目
1、界面如图,
加入菜单项并命名为:menuMain
2、程序代码:
新建代码文件:setMenu.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using DBClassLib;namespace ERP
{
public class SetMenu
{
private MenuStrip msMain; /// <summary>
/// 构造函数
/// </summary>
/// <param name="mMain"></param>
public SetMenu(MenuStrip mMain)
{
msMain
= mMain;
msMain.Visible
= true;

}
/// <summary>
/// 设置菜单权限
/// </summary>
public void SetMenuPower()
{
string strSql;
int mItemCount, i, j;
mItemCount
= msMain.Items.Count;
strSql
= "SELECT FSFormNo,FGfaIsOk FROM t_GroupFormsAuthority WHERE FStatus='1' AND FUGroupNo='" + Global.userInfo[2] + "'";
DBOperator db
= DBOperator.GetDBOperator(Global.strConnection);
DataTable dt
= new DataTable();
db.Open();
dt
= db.GetDataTable(strSql);
if (dt.Rows.Count > 0)
{
for (i = 0; i < mItemCount; i++)
{
for (j = 0; j < dt.Rows.Count; j++)
{
if ((msMain.Items[i].Name.ToString() == dt.Rows[j]["FSFormNo"].ToString()) && (dt.Rows[j][1].ToString() == "1"))
{
SetMenuItemUsability(msMain.Items[i],
true);
GetSubMenu(dt,(ToolStripMenuItem) msMain.Items[i]);
break;
}
else
{
SetMenuItemUsability(msMain.Items[i],
false);
}
}
}
}
else
{
msMain.Visible
= false;
} db.Close(); }
private void GetSubMenu(DataTable dt, ToolStripMenuItem tsmItem)//ToolStripItem mItems)
{
//ToolStripMenuItem tsmItem=new ToolStripMenuItem() ;
int i,j,mItemsCount;
mItemsCount
= tsmItem.DropDownItems.Count; if (mItemsCount > 0)
{
for (i = 0; i < mItemsCount; i++)
{
for (j = 0; j < dt.Rows.Count; j++)
{
if (tsmItem.DropDownItems[i].Name == dt.Rows[j][0].ToString() && dt.Rows[j][1].ToString() == "1")
{
SetMenuItemUsability(tsmItem.DropDownItems[i],
true);
break; }
else
{
SetMenuItemUsability(tsmItem.DropDownItems[i],
false);
}
}
}
}
}
/// <summary>
/// 设置菜单可用性

 

3、主窗口调用:
SetMenu sm = new SetMenu(menuMain);
sm.SetMenuPower();