我試圖將文本文件的每一行添加到listView
中的不同列中。但是,我遇到了一個問題。Add()方法中的If語句?
這是我做了一個方法:
public void OpenFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
string line = "";
int index = 0;
if (openFileDialog.ShowDialog() == true)
using (StreamReader sr = File.OpenText(openFileDialog.FileName))
{
while ((line = sr.ReadLine()) != null)
{
index++;
if (index == 1)
InvoiceNumbertxt.Text = line;
else if (index == 2)
InvoiceDatetxt.Text = line;
else if (index == 3)
DueDatetxt.Text = line;
else if (index == 4 || index == 5 || index == 6 || index == 7 || index == 8 || index == 9)
PersonInfolst.Items.Add(line);
else if (index == 10)
{
Items.Add(new ItemProperties
{
Item = line
if(index == 11)// <---- If-statement inside Add?
Description = line;
});
itemlst.ItemsSource = Items;
}
else
break;
}
}
}
正如你所看到的索引僅僅是一個方便的標誌(變量)來插入,以線條和多行不重疊到相同的控制。
問題我已經是我要檢查,如果指數是內部的Add()方法的值,這樣我可以在新的文本文件行添加到列表中的同一行,但不同的列。
UPDATE:
public partial class MainWindow : Window
{
ObservableCollection<ItemProperties> Items =
new ObservableCollection<ItemProperties>();
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<ItemProperties> GameCollection
{
get
{
if (Items == null)
{
Items = new ObservableCollection<ItemProperties>();
}
return Items;
}
}
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFile();
}
public void OpenFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
string line = "";
int index = 0;
if (openFileDialog.ShowDialog() == true)
using (StreamReader sr = File.OpenText(openFileDialog.FileName))
{
while ((line = sr.ReadLine()) != null)
{
index++;
if (index == 1)
InvoiceNumbertxt.Text = line;
else if (index == 2)
InvoiceDatetxt.Text = line;
else if (index == 3)
DueDatetxt.Text = line;
else if (index == 4 || index == 5 || index == 6 || index == 7 || index == 8 || index == 9)
PersonInfolst.Items.Add(line);
else if (index == 10)
{
Items.Add(new ItemProperties { Item = line });
itemlst.ItemsSource = Items;
}
else if (index == 11)
{
//??
}
else
break;
}
}
}
private void btnOpenImage_Click(object sender, System.Windows.RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog openfile = new Microsoft.Win32.OpenFileDialog();
openfile.DefaultExt = "*.jpg";
openfile.Filter = "Image Files|*.jpg";
Nullable<bool> result = openfile.ShowDialog();
if (result == true)
{
imagefile.Source = new BitmapImage(new Uri(openfile.FileName));
}
}
public class ItemProperties
{
public string Item { get; set; }
public string Description { get; set; }
public string Quantity { get; set; }
public string UnitPrice { get; set; }
public string Tax { get; set; }
}
}
嘗試三元運算符'描述=(索引== 11)?行:「」' –
這段代碼實際上永遠不會運行...因爲當輸入時索引總是10,如果缺少== 10語句 – Legends
注意:在這個例子中,'if(index == 11)'從不爲真,因爲只有在索引== 10的情況下才會添加。 – Nzall