【发布时间】:2021-04-16 12:01:27
【问题描述】:
我有一个文件,其中包含我正在读取的天气信息并将其放入一个结构中,然后我将其添加到列表中。我有一个 dateTimePicker 控件,用户将使用它来选择一月份的日期,当他们这样做时,我需要它打印到 listBox 控件我存储在列表中的那天的日期和天气信息.我已经将文件标记化并放入结构变量并将其添加到列表中。
当我通过 dateTimePicker 控件选择一个日期时,我最终会一次获得所有日期和信息。我相信因为我不明白如何使用 dateTimePicker 控件,所以我无法弄清楚。
所以,当我选择 2018 年 1 月 1 日时,我需要它在 listBox 中引入当天的日期和降水、高温、低温等天气信息。我希望我已经将所有内容解释得足够清楚,以便您理解。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Chapter9_Problem1_
{
public partial class Form1 : Form
{
// create new structure
struct Weather
{
public string date;
public string precipitation;
public string highTemp;
public string lowTemp;
}
// create new list
private List<Weather> weatherList = new List<Weather>();
// method to get info from file and store into list
private void fileData()
{
StreamReader inputFile;
inputFile = File.OpenText("weather.txt");
while(!inputFile.EndOfStream)
{
// create instance of the weather structure
Weather weather = new Weather();
// read the file and store into info variable
string info = inputFile.ReadLine();
// create char array for delimiter
char[] delimiter = { ';' };
// split info by each delimiter
string[] tokens = info.Split(delimiter);
// store the values into the structure weather variables
weather.date = tokens[0];
weather.precipitation = tokens[1];
weather.highTemp = tokens[2];
weather.lowTemp = tokens[3];
// add to the list
weatherList.Add(weather);
}
}
public Form1()
{
InitializeComponent();
}
// dateTimePicker method
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
// call file data method
fileData();
// create datetime object
DateTime dateTime = new DateTime();
// assign datetime object to the datetimepicker control
dateTime = dateTimePicker1.Value;
foreach(Weather weather in weatherList)
{
listBox1.Items.Add(weather.date + weather.date + weather.highTemp + weather.lowTemp);
}
}
}
}
【问题讨论】:
-
此处允许使用仅供参考的段落 :)
-
我在您的代码中没有看到您实际使用日期选择器值的任何地方。当然你将它分配给一个变量 (
dateTime = dateTimePicker1.Value;) ,但你实际上并没有将它用于任何事情。 -
我的建议:将文件中的日期解析为
Weather模型中的DateTime。完成后,您可以根据weather.date.Date == dateTime.Date过滤weatherList。 -
文件中每一行的日期是否总是相同的格式?您能否提供文件中的日期样本?
-
你能告诉我格式吗?也许只是提供文件中的示例日期/时间值?在不知道格式的情况下,我无法编写代码来解析日期。
标签: c# winforms datetimepicker