如何在文本框中添加值? [英] How to add values in a textbox?

查看:92
本文介绍了如何在文本框中添加值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在文本框中输入2 + 1,我有两个文本框第二个文本框应该显示值为3.



我尝试过:



i尝试使用解析。但它不起作用

解决方案

为此,您将扫描TextBox,创建数值,并编写代码以执行算术功能。换句话说,你必须编写一个解析器。这并不容易!



但是,对于简单的数值表达式,您可以使用DataTable对象的'Compute函数:[ ^ ]

  //  以及其他常用参考资料 
使用 System.Data;

// 在某些方法中
var result = new DataTable()。Compute(yourTextBox.Text, null 作为数字。



如果你是.NET新手,我鼓励你专注于基础知识,而不是像这样的代码,这是一种黑客攻击!



但是,如果你必须使用它,让我们展示一个正确的例子;

 private DataTable dTable = new DataTable(); 

公开双倍? EvalText(字符串文本)
{
object result = null;

尝试
{
result = dTable.Compute(text,null);

if(result == null)返回null;

返回Convert.ToDouble(结果);
}
catch(Exception ex)
{
抛出新的ArgumentException(


{text}无法解析为返回double:异常{ex.Message},ex.InnerException);
}
}

使用示例:

 private void yourButton_Click(object sender,EventArgs e)
{
double? result = EvalText(yourTextBox.Text);

if(result!= null)
{
//有效结果
}

}

为什么用'双?因为任何其他数字类型都可以转换为'Double。


您很可能需要阅读 .NET预订Charles Petzold的零点 [ ^ ]。

i have two textboxes if i enter 2+1 in a textbox second textbox should show the value as 3.

What I have tried:

i tried using parse. but its not working

解决方案

To do this you will have scan the TextBox, create numeric values, and write code to perform arithmetic functions. In other words you have to writer a parser. That's not easy !

However, for simple numeric expressions, you can use the 'Compute function of the DataTable object: [^]

// required along with the other usual references
using System.Data;

// in some method
var result = new DataTable().Compute(yourTextBox.Text, null);

But, think carefully if this is a good idea, or not: any mistake in text-box entry is going to cause a crash when the 'Compute function is called. The 'Compute function returns an 'object, which you;ll have to convert to the right Type to use as a number.

If you are new to .NET, I encourage you to focus on basics, not on code like this that is kind of a hack !

But, if you must use it, let's show a proper example;

private DataTable dTable = new DataTable();

public double? EvalText(string text)
{
    object result = null;

    try
    {
        result = dTable.Compute(text, null);

        if (result == null) return null;

        return Convert.ToDouble(result);
    }
    catch (Exception ex)
    {
        throw new ArgumentException(


"{text} cannot be parsed to return double : Exception {ex.Message}", ex.InnerException); } }

Example of use:

private void yourButton_Click(object sender, EventArgs e)
{
    double? result = EvalText(yourTextBox.Text);

    if(result != null)
    {
       // valid result
    }
    
}

Why use 'double ? Because any other numeric Type can be converted to 'Double.


You most likely need to read .NET Book Zero by Charles Petzold[^].


这篇关于如何在文本框中添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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