转发器项目给我空值

时间:2015-08-04 11:20:40

标签: c# asp.net

我有按钮提供投票功能。我使用usercontrol。 我得到以下异常:

  
    

对象引用为空

  

这是代码

protected void btnVot_Click(object sender, EventArgs e)
{
    try
    {
        //Save Data
        sqlCon = DBConnection.GetConnection(string.Empty);

        if (sqlCon != null)
        {
            foreach (RepeaterItem item in rpAnswers.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    VotingAnswers AnswerObj = (VotingAnswers )item.DataItem;
                    HtmlInputRadioButton rbMyRadio = (HtmlInputRadioButton)item.FindControl("rbMyRadio");

                    if (rbMyRadio != null && rbMyRadio.Checked)
                    {
                        VotAns.AnswerCount = +1;
                        VotAns.AnswerRatio = (VotAns.AnswerCount * 100) / 100;

                        if (VotAnswerDAO.Update(sqlCon, VotAns))
                        {
                            divQuestion.Visible = false;
                            divVoting.Visible = true;
                        }
                    }
                }
            }
        }
    }
    catch (Exception)
    {
    }
    finally
    {
        if (sqlCon != null)
        {
            sqlCon.Close();
            sqlCon.Dispose();
        }
    }
    VotingAnswers AnswerObj = (VotingAnswers )item.DataItem;   //is giving me null

你能帮我理解出了什么问题吗?

2 个答案:

答案 0 :(得分:0)

只需在那里添加条件

if(item != null && item.DataItem != null)
{
// Do code....
}

这不是正确的解决方案,但它现在对你有帮助

答案 1 :(得分:0)

我在你的代码中做了一些重构:

protected void btnVot_Click(object sender, EventArgs e)
{
    try
    {
        //Save Data
        sqlCon = DBConnection.GetConnection(string.Empty);
        if (sqlCon == null)
            return;

        foreach (RepeaterItem item in rpAnswers.Items)
        {
            if (item.ItemType != ListItemType.Item && item.ItemType != ListItemType.AlternatingItem)
                continue;

            VotingAnswers AnswerObj = (VotingAnswers )item.DataItem;
            HtmlInputRadioButton rbMyRadio = (HtmlInputRadioButton)item.FindControl("rbMyRadio");

            if (rbMyRadio == null || !rbMyRadio.Checked)
                continue;

            VotAns.AnswerCount = +1;
            VotAns.AnswerRatio = (VotAns.AnswerCount * 100) / 100;

            if (VotAnswerDAO.Update(sqlCon, VotAns))
            {
                divQuestion.Visible = false;
                divVoting.Visible = true;
            }
        }
        VotingAnswers AnswerObj = (VotingAnswers)item.DataItem;        
    }
    catch (Exception ex)
    {
        //Do some exception handling here
    }
    finally
    {
        if (sqlCon != null)
        {
            sqlCon.Close();
            sqlCon.Dispose();
        }
    }
}

并移动该行:

VotingAnswers AnswerObj = (VotingAnswers)item.DataItem;

更安全的位置。

要回答您的问题,如果没有数据库连接或者转发器中的页眉或页脚触发了事件,则会抛出异常。