Reputation: 904
There's a file with such structure:
companyname1;shortname1;identification1;01.01.1980 companyname2;shortname2;identification2;01.01.1987 companyname3;shortname3;identification3;01.01.1990 companyname4;shortname4;identification4;23.01.1995
I want to put all "companynameX" into listbox1 and when each item is clicked then related "identificationX" will be shown in textbox. I'm very stupid and for this simple task I used DataTable. It doesn't work, listbox is filled in with one item, textbox is filled in with this "System.Data.DataRowView". Why it doesn't work and how to do my task in more elegant way?
foreach (string line in File.ReadAllLines(@"D:\file.txt"))
{
string[] parts = line.Split(';');
DataSet ds = new DataSet();
DataTable dt = new DataTable("dt");
DataColumn dc;
DataRow dr;
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "First";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "Second";
dt.Columns.Add(dc);
ds.Tables.Add(dt);
for (int j = 2; j < parts.Length; j += 4)
{
for (int k = 0; k < parts.Length; k += 4)
{
dr = dt.NewRow();
dr["First"] = parts[j];
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Second"] = parts[k];
dt.Rows.Add(dr);
}
}
listBox1.DataSource = dt;
listBox1.DisplayMember = "First";
listBox1.ValueMember = "Second";
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = listBox1.SelectedItem.ToString();
textBox1.Text = value;
}
Upvotes: 0
Views: 596
Reputation: 1038710
var records = from line in File.ReadAllLines(@"D:\file.txt")
let parts = line.Split(';')
select new
{
Company = parts[0],
Identification = parts[2]
};
listBox1.DataSource = records;
listBox1.DisplayMember = "Company";
listBox1.ValueMember = "Identification";
Upvotes: 2