将richtextbox(TimeSpan)的内容转换为Double或Float

Convert the content of richtextbox (TimeSpan) to Double or Float

我是新来的,希望我来对地方了。 谁能帮我 ? 我的程序中有 3 个 richTextBox 第一个是(日期时间格式):日期开始 第二个是(日期时间格式):日期结束 第三个是(时间跨度格式):剩余天数(从 richTextBox1)到下一个日期(richTextBox2)。 我想要的是如果 richTextBox3 <= 0 显示警告消息。 但我不知道如何将项目转换为 Double。 提前致谢。

我的代码:

// Reading Text File 1.
TextReader dateOfStart = new StreamReader (TextFilePath);

richTextBox1.Text = dateOfStart.ReadToEnd();
dateOfStart.Close();

// Reading Text File 2.
TextReader dateOfEnd = new StreamReader (TextFilePath);

richTextBox2.Text = dateOfEnd.ReadToEnd();
dateOfEnd.Close();

// Convert to DateTime 1
DateTime dateStarting = DateTime.Parse(dateOfStart);

// Convert to DateTime 2
DateTime dateEnding = DateTime.Parse(dateOfEnd);

// Calc
TimeSpan remainningDays = dateEnding - dateStarting;

// if richTextBox3 <= Zero, launch Warninng.
If (remainningDays <= 0)
{
    MessageBox.Show (Warnning !!!!!);
}    
double myDoubleValue = Double.Parse(richTextBox3.Text);

格式不正确的数据将导致此方法抛出异常。由于您正在尝试解析直接用户输入,因此您应该将其包装在 try-catch 块中。或者,如果您担心性能,可以使用 TryParseTryParse 方法不会抛出异常。

您可以做一些事情来完成这项工作。

首先,不需要直接使用StreamReader对象,可以使用静态File.ReadAllText()方法将文件内容读入字符串变量。这将打开文件,阅读文本,return,然后为您关闭文件。

richTextBox1.Text = File.ReadAllText(startDateFilePath);
richTextBox2.Text = File.ReadAllText(endDateFilePath);

接下来,在设置 DateTime 变量时,您希望将字符串值传递给它,而不是 StreamReader 对象。由于我们已经将字符串存储在我们的 RichTextBox 对象中,我们可以只使用那些:

// Note that `Parse` will throw an exception if the text is not a valid date
// Use `TryParse` instead if this is a possibility, 
//     or use a `try/catch` block and catch the FormatException
DateTime dateStarting = DateTime.Parse(richTextBox1.Text);
DateTime dateEnding = DateTime.Parse(richTextBox2.Text);

然后,当你做减法时,你可以访问 TimeSpanTotalDays 属性 来获取表示的天数,并设置你的 richTextBox3.Text到那个值:

double remainingDays = (dateEnding - dateStarting).TotalDays;
richTextBox3.Text = remainingDays.ToString();

if (remainingDays <= 0)
{
    MessageBox.Show("Warning !!!!!");
}