对象引用未设置为Object实例

时间:2014-05-15 23:56:48

标签: c#-5.0

大家好日子, 我需要有人帮我查看我的代码。我有这个错误的**对象引用未设置为对象**的实例。看来错误是在这行代码中

if (_scrollingTimer == null) { _scrollingTimer = new Timer() { Enabled = false, Interval = 500, Tag = (sender as TrackBar).Value };

但不幸的是我无法解决这个错误。如果有人可以帮助我,我会很高兴。谢谢你的支持。最好的问候。 Firstoption。 以下是代码的剩余部分。

 byte[] data = new byte[5];
 private Timer _scrollingTimer = null;

  private void button3_Click(object sender, EventArgs e)
        {

            UInt32 numBytesWritten = 0;
            data[0] = 1;
            myFtdiDevice.Write(data, 1, ref numBytesWritten);
            data[0] = 0x6A;
            myFtdiDevice.Write(data, 1, ref numBytesWritten);


        }



  private void trackBar1_Scroll(object sender, EventArgs e)
        {

           if(!backgroundWorker1.IsBusy)
           {

               backgroundWorker1.RunWorkerAsync();
           }

        }

     private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            UInt32 numBytesWritten = 1;
            string dataToWrite = "#0";

            if (_scrollingTimer  == null)
            {
                _scrollingTimer = new Timer()
                {
                    Enabled = false,
                    Interval = 500,
                    Tag = (sender as TrackBar).Value
                };
                _scrollingTimer.Tick += (s, ea) =>
                {
                    if (trackBar1.Value == (int)_scrollingTimer.Tag)
                    {
                        _scrollingTimer.Stop();
                        myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);
                        int percent = (int)(((double)trackBar1.Value / (double)trackBar1.Maximum) * 100);
                        label2.Text = (percent.ToString()) + "%";
                        data[0] = Convert.ToByte(percent);
                        data[1] = 0x6A;
                        myFtdiDevice.Write(data, 2, ref numBytesWritten);
                        _scrollingTimer.Dispose();
                        _scrollingTimer = null;
                    }
                    else
                    {
                        _scrollingTimer.Tag = trackBar1.Value;
                    }
                };
                _scrollingTimer.Start();
            }
        }

1 个答案:

答案 0 :(得分:0)

sender不是TrackBar。看起来可能是backgroundWorker1