2011-07-04 38 views
2

我正在使用C#代碼從Mettler Toledo縮放設備讀取數據。使用C#從Mettler Toledo縮放設備讀取數據

這裏是我的完整代碼:

private SerialPort port = new SerialPort("COM1", 4800, Parity.None, 8, StopBits.One); 

public Inwardsfrm() 
{ 
    InitializeComponent(); 
    port.DtrEnable = true; 
    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
} 

private void Inwardsfrm_Load(object sender, EventArgs e) 
{ 
    if (port.IsOpen == false) 
    try 
    { 
     port.Open(); 
    } 
    catch (Exception oex) 
    { 
     MessageBox.Show(oex.ToString()); 
    } 
} 

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    this.Invoke(new EventHandler(DoUpdate)); 
} 


private void DoUpdate(object s, EventArgs e) 
{ 
    Thread.Sleep(30); 
    string data = port.ReadExisting() + port.ReadExisting(); 
    try 
    { 
     richTextBox1.Text = data.Trim().Remove(0, 3); 
    } 
    catch (Exception f) 
    { 
     MessageBox.Show(f.Message.ToString()); 
    } 
} 

它的正常工作,並顯示在一個名爲richTextBox1標籤的結果,但一段時間後它提供了以下錯誤:

Index and count must refers to location with the string Parameter Name :Count

有什麼不對?我該如何解決它?

+0

你在做什麼 - > string data = port.ReadExisting()+ port.ReadExisting(); – dbasnett

回答

0

看來問題是由Remove()方法引起的,Trim()後面的數據中剩下的字符少於3個字符。

嘗試:

private void DoUpdate(object s, EventArgs e) 
    { 
     Thread.Sleep(30); 
     string data = port.ReadExisting() + port.ReadExisting(); 
     if(data.Trim().Count() < 3) 
      MessageBox.Show("data = " + data); 
     else 
     try 
     {  
      richTextBox1.Text = data.Trim().Remove(0, 3); 
     } 
     catch (Exception f) 
     { 
      MessageBox.Show(f.Message.ToString()); 
     } 
    } 

這將有助於弄清楚。