代码是在Visual Studio 2012上完成的c#Windows窗体应用程序,该任务的目的是在GUI中使用字典来添加,删除和搜索书籍。
我已经列出了我的gui应用程序,它包含4个按钮,2个文本字段,2个复选框列表,然后是一些标签来解释它们的用途。
button3
应该使用ISBN激活搜索。 (用户在textbox1
中输入ISBN,然后所有包含其中一部分的书籍将匹配)
这是我的表单代码
Dictionary<string, Book> library = new Dictionary<string, Book>();
public Form1()
{
InitializeComponent();
button1.Text = "Add Book";
button2.Text = "Remove Book";
button3.Text = "Search Using ISBN";
button4.Text = "Search Using Title";
label1.Text = "Enter ISBN below";
label2.Text = "Enter Title below";
label3.Text = "Tick boxes on the left display if a book is loaned or not";
label4.Text = "All books found after search";
}
public void Update()
{
checkedListBox1.Items.Clear();
foreach (var pair in library)
{
checkedListBox1.Items.Add(pair.Value);
}
}
private void button1_Click(object sender, EventArgs e) //Add Button
{
if (textBox1.Text != "" && textBox2.Text != "")
{
library[textBox1.Text] = new Book(textBox1.Text, textBox2.Text);
Update();
}
}
private void button2_Click(object sender, EventArgs e) //Remove Button
{
library.Remove(textBox1.Text);
Update();
}
private void button3_Click(object sender, EventArgs e) //ISBN Search Button
{
}
}
和Book课程。
class Book
{
private String isbn;
private string title
private Boolean onloan = false;
public Book(string isbn, string title)
{
this.isbn = isbn;
this.title = title;
}
public string ISBN
{
get { return isbn; }
set { isbn = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
override public String ToString()
{
return this.ISBN + " " + this.Title;
}
}
我正在与button3
挣扎。我在textbox1
中输入了一个ISBN的部分位,然后单击按钮,然后应该查看字典,如果找到任何与之匹配的书,则会在另一个checklistbox2
中显示它们。
我已经尝试了很多方法将它们显示在checklistbox2
中,但是当我点击按钮时,checklistbox2
中没有显示任何内容。
我真的很难过如何做到这一点。
我试过了。
修改
我发现我出错的地方,我的逻辑没有错,遗憾的是我的form.design.cs没有包含
this.button3.Click += new System.EventHandler(this.button3_Click);
我现在已经修复了这一切,一切正常。
答案 0 :(得分:0)
您可以使用lambda表达式
private void button3_Click(object sender, EventArgs e) //ISBN Search Button
{
checkedListBox2.Items.Add(_library.First(i => i.Key == textBox1.Text).Value);
}
答案 1 :(得分:0)
在我的 Form1.Designer.cs 中我没有包含
this.button3.Click += new System.EventHandler(this.button3_Click);
我添加了这个,我的代码正常工作,我用
private void button3_Click(object sender, EventArgs e) //ISBN Search Button
{
checkedListBox2.Items.Clear(); //clears list on click
foreach (var pair in library)
{
if (pair.Key.Contains(textBox1.Text))
{
checkedListBox2.Items.Add(pair.Value);
}
}
}
感谢所有评论帮助我的人。