程序如下:public partial class Form1 : Form
    {
        private SqlCeConnection cn;
        private SqlCeCommand cmd;
        int i = 0;
        public Form1()
        {
            InitializeComponent();
            this.timer1.Interval = 1000;
            timer1.Enabled = true;
            
        }        private void timer1_Tick(object sender, EventArgs e)
        {
            SqlCeConnection cn = null;            try
            {
                
                cn.ConnectionString = @"Data Source =F:\database\database\sqlmobile.sdf;";
                cn.Open();
                SqlCeCommand cmd = cn.CreateCommand();
                cmd.CommandText = "学生信息表";
                cmd.CommandType = CommandType.TableDirect;
                SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds, "学生信息表");
                i++;
                Console.WriteLine("{0}",i);
                
                while (i<3)
                {
                    DataRow dr = ds.Tables["学生信息表"].Rows[i];
                    this.textBox1.Text = dr[0].ToString();
                    this.textBox2.Text = dr[1].ToString();
                    this.textBox3.Text = dr[2].ToString();
                    
                    timer1.Enabled = false;
                }
                         }
            catch (SqlCeException sqlex)
            {
                foreach (SqlCeError sqlerror in sqlex.Errors)
                { MessageBox.Show(sqlerror.Message); }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            finally { if (cn.State!= ConnectionState.Closed) { cn.Close(); } }//此处出错:未处理NullReferenceException
        }        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“sqlmobileDataSet.学生信息表”中。您可以根据需要移动或移除它。
            this.学生信息表TableAdapter.Fill(this.sqlmobileDataSet.学生信息表);        }
    } 平台是:vs.net2005、sql ce数据库

解决方案 »

  1.   

    SqlCeConnection cn = null; 
    删除了看看
      

  2.   

    错误原因是有一个引用的值为null,但你却使用了它,可能是你的timer设的间隔过短,导致有些变量还没初始化好,就拿来用了
    而且 你的i 一开始为0,走到循环中 timer就停用了,应该也有问题
      

  3.   

    SqlCeConnection cn = null;
    try
    {
       cn = new SqlConnection();  // 必须先创建对象
       cn.ConnectionString = @"Data Source =F:\database\database\sqlmobile.sdf;";
       cn.Open(); 
       //
    }
    catch
    {
    }