Reputation: 3
i'm making simple program, and i'm stuck on simple question. How can i compare two lists with objects , find that object and print all class elements that belongs to that object?
List<Skaitytojas> MyObjectList = new List<Skaitytojas>();
List<Knyga> KnyguList = new List<Knyga>();
private void button2_Click(object sender, EventArgs e)
{
Reader reader = new Reader();
reader._surname = Convert.ToString(textBox1.Text);
reader._id = Convert.ToInt32(textBox2.Text);
MyObjectList.Add(reader);
MessageBox.Show("you created new user");
}
private void button4_Click(object sender, EventArgs e)
{
Book new_book = new Book();
new_book.book_id = Convert.ToInt32(textBox3.Text);
new_book.date1 = Convert.ToString(textBox4.Text);
new_book.date2 = Convert.ToString(textBox5.Text);
new_book.date3 = Convert.ToString(textBox6.Text);
new_book._id2 = Convert.ToInt32(textBox7.Text);
BookList.Add(new_book);
MessageBox.Show("you added new book!");
}
I want to compare reader._id with new_book.id2, its gonna be same number , and if i find it i want to print all information about it: book id,date1,date2 etc. But i don't know how to do it, i tried it this way:
public void print_book(int x, ListBox f)
{
List<Book> BookList = new List<Book>();
foreach (var k in BookList)
{
if (x == k._id2)
{
f.Items.Add(x);
}
}
}
Call function with button
private void button3_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox2.Text);
Metodai m = new Metodai();
m.print_book(x, this.listBox1);
}
When i try to do this function the list is still empty, whats wrong with it? Maybe there is another way to do it? Can you help me?
Upvotes: 0
Views: 227
Reputation: 2062
You created a function variable 'BookList' with the same name as that of instance variable.
There are two ways to fix it.
// Fix #1
public void print_book(int x, ListBox f)
{
//List<Book> BookList = new List<Book>(); // Comment this line
foreach (var k in BookList)
{
if (x == k._id2)
{
f.Items.Add(x);
}
}
}
// Fix #2
public void print_book(int x, ListBox f)
{
List<Book> BookList = new List<Book>(); // 'BookList' has never been used
foreach (var k in this.BookList) // Add 'this'
{
if (x == k._id2)
{
f.Items.Add(x);
}
}
}
Upvotes: 0
Reputation: 2835
The line
foreach (var k in BookList)
You've just instantiated BookList in the line before so it's looping through nothing.
Upvotes: 1