我正在阅读一个看起来很像字符串的文件
PrId Name Quantity Price Date
3 Milk 2 100 23-08-15
我有一个按钮 - btnDat_Click。当我单击它时,它会检索名为listDate的列表框中的所有日期。我创建了一个名为btnDataToTb_Click的按钮,我需要选择日期,当我点击按钮时,它将显示该日期所有产品的属性(ID,名称,数量)。
PrId Name Quantity Price
3 Milk 2 100
这是整个代码
char[] cc = new char[500]; int i, nr;
string[] lines = new string[250];
public void btnRead_Click(object sender, EventArgs e)
{
string FileName = textBox1.Text;
FileStream r_stream = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
StreamReader reads_string_from_r_stream = new StreamReader(r_stream);
i = 0;
listBox1.Items.Clear();
listBox2.Items.Clear();
for (; ; i++)
{
textBox1.Text = reads_string_from_r_stream.ReadLine();
lines[i] = textBox1.Text;
listBox1.Items.Add(lines[i]);
listBox2.Items.Add(lines[i]);
if (reads_string_from_r_stream.EndOfStream.Equals(true)) goto nn;
}
nn:
textBox2.Text = reads_string_from_r_stream.EndOfStream.ToString();
r_stream.Close();
nr = listBox1.Items.Count;
textBox6.Text = nr.ToString();
}
private void SelectPath_Click(object sender, EventArgs e)
{
OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.Filter = "Text Files|*.txt";
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
textBox1.Text = openFile1.FileName;
}
public void button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt16(textBox6.Text);
ListB.Items.Clear();
for (i = 0; i < n; i++)
{
ListB.Items.Add(lines[i]);
}
}
private void btnDat_Click(object sender, EventArgs e)
{
int n = Convert.ToInt16(textBox6.Text);
for (i = 0; i < n; i++)
{
if(! listDate.Items.Contains(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]))
{
listDate.Items.Add(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]);
}
}
listData.Items.RemoveAt(0);
}
private void btnDataToTb_Click(object sender, EventArgs e)
{
if (listData.SelectedItems.Count > 0)
{
string data = listData.SelectedItem.ToString();
string[] date = data.Split('-');
int day = Convert.ToInt32(date[0]);
int month = Convert.ToInt32(date[1]);
int year = Convert.ToInt32(date[2]);
DateTime a = new DateTime(year, month, day);
for (i = 0; i < listBox2.Items.Count; i++)
{
DateTime data2 = DateTime.Parse(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]);
int result = DateTime.Compare(a, data2);
if(result == 0)
listBox3.Items.Add(string.Format("{0}\t{1}\t{2}\t{3}", lines[i].Split('\t')[0], lines[i].Split('\t')[1], lines[i].Split('\t')[2], lines[i].Split('\t')[3]));
}
}
else
{
MessageBox.Show("Select a date");
}
}
答案 0 :(得分:1)
我说你错了这个问题。而不是读取数据,将它们存储在列表框中,然后在需要时再次读取和解析它们,这非常复杂,你应该这样做:
Item
),其中包含产品ID,名称,数量,价格和日期的属性。List<Item>
中。
IDisposable
/的方法都有Dispose()
方法)时,您应该在using
块中使用它们(如using (StreamReader sr = …) { /* work with sr here */ }
);这将在使用后自动释放对象。var onThisDate = itemList.Where(item => item.Date == selectedDate)
。 Linq还有许多用于选择,过滤和投影数据的功能。