C# 创建动态菜单和子菜单,然后将此错误
这就是错误:C# 创建动态菜单和子菜单,然后将此错误,c#,C#,这就是错误: DataSet ds = new DataSet(); DataTable dt = new DataTable(); string sql = "Select * from MenuControl"; SqlDataAdapter da = new SqlDataAdapter(sql, con); da.Fill(ds); dt = ds.Tables[0]; foreach (DataRow dr in dt.Select("ParentId=" + 0)) { if
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sql = "Select * from MenuControl";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Select("ParentId=" + 0))
{
if (dr["MenuName"] != null && dr["MenuId"] != null && dr["LocationUrl"] != null)
{
menuBar.Items.Add(new MenuItem(dr["MenuName"].ToString(), dr["MenuId"].ToString(), "", dr["LocationUrl"].ToString()));
}
}
foreach (DataRow dr in dt.Select("ParentId>" + 0))
{
if (dr["MenuName"] != null && dr["MenuId"] != null && dr["LocationUrl"] != null)
{
MenuItem mnu = new MenuItem(dr["MenuName"].ToString(), dr["MenuId"].ToString(), "", dr["LocationUrl"].ToString());
if (dr["ParentId"] != null)
{
menuBar.FindItem(dr["ParentId"].ToString()).ChildItems.Add(mnu);
}
}
}
如果FindItem返回null?在设置子项之前添加空检查
System.NullReferenceException: Object reference not set to an instance of an object.
if (dr["ParentId"] != null)
Line 56: {
Line 57: menuBar.FindItem(dr["ParentId"].ToString()).ChildItems.Add(mnu);
Line 58: }
Line 59: }
您可能需要查找应用程序中使用的控件FindItem的文档,根据需要提供值路径(如rootname、child1、child11)的方法,但这取决于您使用的应用程序类型和控件 没有valuePath dr[ParentId]的菜单项,如果需要,请添加空检查,如Damith所示。Othwerwise修复没有此类项目的原因。
var item = menuBar.FindItem(dr["ParentId"].ToString());
if(item !=null)
item.ChildItems.Add(mnu);