0

大家好。我希望有人可以帮助我解决我不明白的两个问题。

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        // If the com port has been closed, do nothing
        if (!comport.IsOpen) return;

        // This method will be called when there is data waiting in the port's buffer

        // Determain which mode (string or binary) the user is in

            // Read all the data waiting in the buffer
            string data = comport.ReadExisting();
            textBox1.AppendText(data);
            textBox1.ScrollToCaret();
            //scnbutton.PerformClick();

            // Display the text to the user in the terminal


    }

我正在处理条形码。当我的扫描仪扫描条形码时,它返回 S08A07934068721。每次 UPC 为 07934068721 时,它都会返回此值,这是我希望附加到文本框的值。

     string data1= data.Substring(4);
     textBox1.AppendText(data1);

这是尝试使用子字符串的示例。

每次我尝试对字符串数据进行子串化时,它最终都会分解成碎片,我不知道如何阻止它。修复此问题后,我将遇到以下代码的问题

textBox1.Text = textBox1.Text.PadLeft(13, '0');

这很好用,并且总是填充 13 位数字。但是,当 UPC 或其他类型的前面有 0 时,它会下降到 12 位,这是为什么呢?

4

2 回答 2

0

我在一段代码中尝试了你的字符串,一切正常。

string data = "S08A07934068721";                // results

string data1 = data.Substring(4);               //   07934068721

// test if padding correctly
string padded = data1.PadLeft(13, '0');         // 0007934068721

// textbox tbPadded is empty before adding text  
tbPadded.AppendText(data1);                     //   07934068721

// pad text
tbPadded.Text = tbPadded.Text.PadLeft(13, '0'); // 0007934068721
于 2013-05-26T00:09:35.213 回答
0

After Much Playing around i discovered there there where invisible character in my textbox so using

textBox1.Text = textBox1.Text.Trim();

This got rid of the invisible characters allowing the padding to work correctly, i then changed my data received event to be on a timer to avoid cross thread issues like this

private void timer3_Tick(object sender, EventArgs e)
    {

        data = comport.ReadExisting();

        try
        {
            if (data != "")
            {
                textBox1.Clear();
                textBox1.AppendText(data);
                timer3.Stop();
                scan();
                timer3.Start();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        comport.DiscardInBuffer();

    }

My program is now working like i need. Thank you user2019047 for your help

于 2013-05-29T13:06:57.993 回答