InfoB infoB = new InfoB();        public FrmVerification(Info info)
        {
            InitializeComponent();
            infoB = info as InfoB;
            inital();
        }        private void inital()
        {
            string sql = string.Format("select * from Info where url = '{0}'", infoB.URL);
            SqlConnection conn = DBHelper.GetConnection();
            SqlCommand command = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    infoB.Question1 = reader["Question1"].ToString();
                    infoB.Question2 = reader["Question2"].ToString();
                    infoB.Question3 = reader["Question3"].ToString();
                    infoB.Answer1 = reader["answer1"].ToString();
                    infoB.Answer2 = reader["answer2"].ToString();
                    infoB.Answer3 = reader["answer3"].ToString();
                }
                reader.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("系统错误" + ex);
            }
            conn.Close();
        }
为什么string sql = string.Format("select * from Info where url = '{0}'", infoB.URL);报错说未将对象引用设置到对象的实例。

解决方案 »

  1.   

    infoB 为 null了是下面这句导致的infoB = info as InfoB;
    -------------------------
    info 为null 或者不能转换成 InfoB 时InfoB就为null
      

  2.   

    InfoB是Info的子类啊...为什么不能转换呢?
      

  3.   

    infoB = info as InfoB;
    inital();
    ------------------------>
    infoB = info as InfoB;
    if(infoB!=null)
    {
       inital();
    }
      

  4.   


    假如为null怎么办?  inital()需要info的属性啊
      

  5.   

    父类不能强制往子类转换
    as 转换不成功,则为null
      

  6.   


    InfoB是Info的子类?你看有那个父类能转换成子类的
      

  7.   

    infoB = info as InfoB;
      inital();
    ----------->
    infoB.URL=info.URL;
    inital();
      

  8.   

    info是从list<Info> infos里提取的  往infos里添加时写的是(new InfoB(...))啊  这样也不能转换吗?
      

  9.   

    这里又new  又as的,为何不直接用info呢,也不用new,直接等号就完事!
      

  10.   

    在inital()方法中加一个判断if(infoB!=null)然后再使用infoB
      

  11.   

    明白了...谢谢 我把infoB = info as InfoB;改成 infoB.URL = info.URL 
     然后运行到  infoB.Question1 = reader["Question1"].ToString();时报错说IndexOutOfRangeException
    我确定数据库中Question1里有值