源代码如下:问题出在 foreach (DataRow row in dsRead.Tables[0].Rows)这句话上,出现的问题如下所示:
未将对象引用设置到对象的实例。 
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。源错误: 行 57:         //DataRow row = null;
行 58: 
行 59:         foreach (DataRow row in dsRead.Tables[0].Rows)
行 60:         {
行 61: 源文件: e:\softbak\experimentmanage修改后\experimentmanage\open_experiment\teacher\get_data_from_excel.aspx.cs    行: 59 堆栈跟踪: [NullReferenceException: 未将对象引用设置到对象的实例。]
   open_experiment_teacher_get_data_from_excel.SubmitBtn_Click(Object sender, ImageClickEventArgs e) in e:\softbak\experimentmanage修改后\experimentmanage\open_experiment\teacher\get_data_from_excel.aspx.cs:59
   System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +75
   System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +115
   System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4919
----------下面是源代码----------
public partial class open_experiment_teacher_get_data_from_excel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Session["xueyuan_id"] = "03";
            this.Session["lab_id"] = "0302";
        }
    }    private static int getMaxID(String xueyuan_id, String lab_id)
    {
        SqlDataReader sdr = BigdaddySP.SelectSomethingNoPageWithWhere_SqlDataReader("V_getMaxProjectID", "xueyuan_id='" + xueyuan_id + "' and lab_id='" + lab_id + "'");
        if (sdr.Read())
        {
            return  Convert.ToInt32(sdr["max_id"].ToString());
        }
        sdr.Close();
        return 0;
    }
    private static String computeProjectID(int id)
    {
        String str = Convert.ToString(id);
        if (str.Length == 1)
            return "000" + str;
        else if (str.Length == 2)
            return "00" + str;
        else if (str.Length == 3)
            return "0" + str;
        else if (str.Length == 4)
            return str;
        else return "0000";
    }
    protected void SubmitBtn_Click(object sender, ImageClickEventArgs e)
    {
        //tecselclassid,name,url,_time        ViewState["excel_name"] = excel_name.Text;
        DataSet dsRead= CreateDataSource(ViewState["excel_name"].ToString());
        //DataRow row = null;
------------------------------------
        foreach (DataRow row in dsRead.Tables[0].Rows)//???????????
--------------------------------       
         {            int pro_id=getMaxID(this.Session["xueyuan_id"].ToString(),this.Session["lab_id"].ToString())+1;
            
            int iRet = 0;
            SqlParameter[] prams = {        
            DataBase.MakeInParam("@id", SqlDbType.Int, 4,row["id"].ToString()),
            DataBase.MakeInParam("@name", SqlDbType.VarChar, 50,row["姓名"].ToString()),
            DataBase.MakeInParam("@type", SqlDbType.VarChar, 50,row["type"].ToString()),
            DataBase.MakeInParam("@request", SqlDbType.VarChar, 50,row["请求"].ToString()),
            DataBase.MakeInParam("@xueyuan_id", SqlDbType.VarChar, 2,this.Session["xueyuan_id"].ToString()),
            DataBase.MakeInParam("@lab_id", SqlDbType.VarChar, 4,this.Session["lab_id"].ToString()),
            DataBase.MakeInParam("@project_id", SqlDbType.VarChar, 4,computeProjectID(pro_id))           
                                        };
            iRet = DataBase.RunProcInsert("insert_project", prams);
            if (iRet > 0)
            {
                message.Text = "<script>this.alert('信息提交成功.')</script>";
            }
            else
            {
                message.Text = "<script>this.alert('信息提交失败.')</script>";
            }
        }
        DataSet ds = BigdaddySP.SelectSomethingNoPageWithWhere_DataSet("open_project", "1=1");
        list.DataSource = ds.Tables[0].DefaultView;
        list.DataBind();
        //Databind();
    }    public static DataSet CreateDataSource(string Src)
    {
        try
        {
            string strConn;            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=" + Src + ";" +
            "Extended Properties=\"Excel 8.0;IMEX=1;\"";//连接            OleDbConnection conn = new OleDbConnection(strConn);            conn.Open();            System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);            string tableName = schemaTable.Rows[0][2].ToString().Trim();//得到excel表名            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [" + tableName + "]", strConn);//查找excel数据            DataSet myDataSet = new DataSet();//定义数据            myCommand.Fill(myDataSet);            conn.Close();            return myDataSet;
        }
        catch
        {
            return null;
        }
    }}

解决方案 »

  1.   


    if(ds.Tables[0].Rows.Count > 0)//遍历前先确保rows有值
    {
      for(int i=0;i<ds.Tables[0].Rows.Count;i++)
      {  }
    }
      

  2.   

    dsRead可能是null,你跟踪下CreateDataSource方法,看看是不是出异常了,返回null
      

  3.   

    我不知道为什么foreach这里会出问题,之前也做了一个测试的程序,就是把数据从excel里读出来,并显示,发现一切都是正常的,可当我对原先的代码进行改进,即增加了往数据库写数据的功能,数据先从excel里取出放到dataset,然后在通过foreach循环来把dataset中的数据放入相应的数据库,但不知道为什么foreach这里出现问题,请各位大侠告知,谢谢。
      

  4.   

    断点看下dsRead是否取到数据了,在使用dsRead之前,先判断一下dsRead是否为空
      

  5.   

    if(ds != null && ds.Tables[0].Rows.Count > 0)//遍历前先确保rows有值
    {
      for(int i=0;i<ds.Tables[0].Rows.Count;i++)
      {  }
    }
      

  6.   

    我在foreach这句话里设置了一个断点,但是发现一件很奇怪的现象,原本foreach程序之前会调用createdatasource()方法,但是当我进入createdatasource()方法内部的时候,想看看里面的一些变量的值的时候,我发现出现问题了,很多都是null,比如数据库连接的strConn,也是null?不知道为什么,得出的dsRead好像也是null的,问题出现在哪里
      

  7.   

    为什么我这里会出现dsRead==null,而我通过
    DataSet ds= CreateDataSource(ViewState["excel_name"].ToString());
     list.DataSource = ds.Tables[0].DefaultView;
            list.DataBind();
    然后在aspx页面里设置相应的表格显示list里的数据都是很正常的,为什么同样的createdatasource语句,在使用foreach的时候就出现null的结果,为什么?
      

  8.   

    看看你的createdatasource()里面 catch异常 看看错误提示?catch(Exception ex)
    {
       MessageBox.Show(ex.ToString());//看看这里的信息
       return null;
    }
      

  9.   

    CreateDataSource代码怎么会出现问题呢,之前从excel表格里读出里面的数据时候用的就是这个代码,没有任何的修改,怎么会有问题呢,呵呵,jiatong1981不好意思,我现在机子上没有装。net,代码也都在实验室的机子上,我现在没法按照您的意思进行调试。只是觉得问题应该不在createdatasource里面,但是我有无法解释为什么读不出数据,我想起来了,我当时excel表格是打开着的,这个难道导致了错误???
      

  10.   

    “未将对象引用设置到对象的实例:”
    1. 同意jiatong1981(末日之痕),这是个典型的错误,你的dataset为null,以后一定要加上
       if(ds != null && ds.Tables[0].Rows.Count > 0这些话,保证程序的容错性。
    2. 我当时excel表格是打开着的,这个难道导致了错误???
       应该是的,你的Excel.exe进程打开的时候未必允许oledb的链接。我经常遇到此类情况,但是你程序跑起来以后,再去打开Excel不会有问题。