使用C#梅特勒 - 托利多大规模的设备读取数据 [英] Reading data from Mettler Toledo scale device using C#

查看:1190
本文介绍了使用C#梅特勒 - 托利多大规模的设备读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C#code读取梅特勒 - 托利多大规模设备的数据。

I am reading data from a Mettler Toledo scale device by using C# code.

下面是我的完整code:

Here is my complete code:

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 标签,但一段时间后它提供了以下错误:

It's working fine and shows the result in a label named richTextBox1, but some time it gives the following error:

索引和计数必须是指位置与字符串参数名称:计数

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

什么是错的?我该如何解决这个问题?

What is wrong? How can I fix it?

推荐答案

看来,这个问题是由remove()方法,还有不到3个字符留在数据修剪()。在

It seems that the problem is caused by the Remove() method, there are less then 3 chars left in data after Trim().

尝试:

 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());
        }
    }

这将有助于找到答案。

这篇关于使用C#梅特勒 - 托利多大规模的设备读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆