我有这样的功能
public bool CheckMentorAccess()
{
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
if (intNoOfMembers > 0)
{
blnAllow = true;
}
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}
然后我就像这样使用
if ((Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
但它在
上面的示例的第一行抛出了一个空引用异常任何人都可以帮助我..
答案 0 :(得分:1)
你可以尝试
if (Session["ROLE_ID"] != null && (Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
在使用ToString之前,首先检查Session["ROLE_ID"]
是否存在。
使用Convert.ToString总是更安全。
答案 1 :(得分:0)
好吧,如果堆栈跟踪只指向该行,我猜这就是问题所在:
Int32.Parse(Session["ROLE_ID"].ToString())
如果NullReferenceException
返回null,那将抛出Session["ROLE_ID"]
。
(如果会话中存在该值但它不是有效整数,则会抛出FormatException
。)
这可能是对CheckMentor()
的调用失败了,当然 - 但是你的堆栈跟踪应该这样说。例如,如果cSQLHelper
为空,那可能会失败。
答案 2 :(得分:0)
尝试此操作 - 检查调用方法时使用的值:
if (Session["ROLE_ID"] != null)
{
if ((Int32.Parse(Session["ROLE_ID"]) == 3) && (CheckMentorAccess()))
{
cmbempList.Visible = true;
}
}
并检查方法
public bool CheckMentorAccess()
{
if (Session["UserID"] == null)
{
throw new NullReferenceException("UserID is null");
}
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
blnAllow = intNoOfMembers > 0;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}