温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在C#中使用TextBox作数据输入方法

发布时间:2021-06-01 16:17:13 来源:亿速云 阅读:220 作者:Leah 栏目:开发技术

怎么在C#中使用TextBox作数据输入方法?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

读取TextBox控件中数据并发送

private void Botton_Float_Click(object sender, EventArgs e)
 {
     if (button1.Text == "关闭串口")
     {
         if(TextBox_Tem_Cal.Text != String .Empty) //判断数据输入框是否为空
         {
             HexMath CRC = new HexMath();
             Byte[] buffer = new Byte[6];
             
             float tem_cal_float = float.Parse(TextBox_Tem_Cal.Text);
             Byte[] float_byte_array = new Byte[4];
             float_byte_array = FloatToBytes(tem_cal_float);

             buffer[0] = float_byte_array[0];
             buffer[1] = float_byte_array[1];
             buffer[2] = float_byte_array[2];
             buffer[3 ] = float_byte_array[3];
             
             CRC.CalculateCrc16(buffer, out buffer[5], out buffer[4]);
             serialPort1.Write(buffer, 0, 6);
         }
        else
         {
             MessageBox.Show("校准数据不能为空");
         }
     }
     else
     {
         MessageBox.Show("串口未打开");
     }
 }

限制TextBox控件输入数据

private void TextBox_Tem_Cal_KeyPress(object sender, KeyPressEventArgs e)//在TextBox中按下按键时触发事件,保证只能输入数字
{
    //判断按键是不是要输入的类型。
    if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
        e.Handled = true;

    //小数点的处理。
    if ((int)e.KeyChar == 46)                           //小数点
    {
        if (TextBox_Tem_Cal.Text.Length <= 0)
            e.Handled = true;   //小数点不能在第一位
        else
        {
            float f;
            float oldf;
            bool b1 = false, b2 = false;
            b1 = float.TryParse(TextBox_Tem_Cal.Text, out oldf);
            b2 = float.TryParse(TextBox_Tem_Cal.Text + e.KeyChar.ToString(), out f);
            if (b2 == false)
            {
                if (b1 == true)
                    e.Handled = true;
                else
                    e.Handled = false;
            }
        }
    }
}

Float 与 byte数组 互转

private static byte[] FloatToBytes(float data) 
{
    unsafe
    {
        byte* pdata = (byte*)&data;
        byte[] byteArray = new byte[sizeof(float)];
        for (int i = 0; i < sizeof(float); ++i)
            byteArray[i] = *pdata++;
        return byteArray;
    }
}
private static float BytesToFloat(byte[] data)
{
    unsafe
    {
        float a = 0.0F;
        byte i;
        byte[] x = data;
        void* pf;
        fixed (byte* px = x)
        {
            pf = &a;
            for (i = 0; i < data.Length; i++)
            {
                *((byte*)pf + i) = *(px + i);
            }
        }
        return a;
    }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI