我正在构建一个应用程序,它将数据输入到一个列表中,使用一个选项卡上的输入文本框(比如表1)。当您点击命令按钮时,它会将数据(书号,作者,标题,流派,页数和发布者)添加到列表(书籍)中。
然后在选项卡2的列表框中显示该书的标题。当您单击选项卡2上列表框中的项目时,我希望它将您在选项卡1上输入的所有信息重新显示到选项卡2上的文本框中但我无法获得信息。
下面是我的代码,包括我为该项目创建的类。
class Book
{
//attributes
private string callNumber;
private string bookTitle;
private string authorName;
private string genre;
private int numberOfPages;
private string publisher;
//constructor
public Book()
{
}
//accessor
public void SetNumber(string aNumber)
{
callNumber = aNumber;
}
public void SetTitle(string aTitle)
{
bookTitle = aTitle;
}
public void SetAuthor(String aName)
{
authorName = aName;
}
public void SetGenre(String aGenre)
{
genre = aGenre;
}
public void SetPages(int aPageNumber)
{
numberOfPages = aPageNumber;
}
public void SetPublisher(String aPublisher)
{
publisher = aPublisher;
}
public string GetNumber()
{
return callNumber;
}
public string GetTitle()
{
return bookTitle;
}
public string GetAuthor()
{
return authorName;
}
public string GetGenre()
{
return genre;
}
public int GetPages()
{
return numberOfPages;
}
public string GetPublisher()
{
return publisher;
}
}
public partial class Form1 : Form
{
List<Book> books;
public Form1()
{
InitializeComponent();
this.books = new List<Book>();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Book aBook = new Book();
aBook.SetNumber(txtCallNumber.Text);
aBook.SetAuthor(txtAuthorName.Text);
aBook.SetTitle(txtBookTitle.Text);
aBook.SetGenre(txtGenre.Text);
aBook.SetPages(int.Parse(txtNumberOfPages.Text));
aBook.SetPublisher(txtPublisher.Text);
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Clear();
}
txtCallNumber.Focus();
txtAuthorName.Clear();
txtBookTitle.Clear();
txtCallNumber.Clear();
txtGenre.Clear();
txtNumberOfPages.Clear();
txtPublisher.Clear();
lstLibrary.Items.Add(aBook.GetTitle());
}
}
private void lstLibrary_SelectedIndexChanged(object sender, EventArgs e)
{
int index = 0;
foreach (Book book in books)
{
string tempTitle;
tempTitle = book.GetTitle();
if (tempTitle == (string)lstLibrary.SelectedItem)
break;
else
{
index++;
}
txtNumberRecall.Text = books[index].GetNumber();
txtTitleRecall.Text = books[index].GetTitle();
txtAuthorRecall.Text = books[index].GetAuthor();
txtGenreRecall.Text = books[index].GetGenre();
txtPagesRecall.Text = Convert.ToString(books[index].GetPages());
txtPublisherRecall.Text = books[index].GetPublisher();
break;
}
}
}
}
我再次尝试从列表框中获取信息(在点击事件中)以显示在文本框中。
答案 0 :(得分:0)
这样的事情会起作用吗?
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
foreach (string s in listBox1.Items)
{
i++;
if (i == 1)
{
textBox1.Text = s;
}
if (i == 2)
{
textBox2.Text = s;
}
if (i == 3)
{
textBox3.Text = s;
}
}
}
答案 1 :(得分:0)
在btnAdd_Click方法中,您永远不会保存您创建的新aBook。您需要将它添加到书籍集合中。将标题添加为lstLibrary.Items中的条目实际上并不保存新创建的对象。
此外,您应该检查循环结构。在btnAdd_Click()中,对于表单上存在的每个控件,您似乎会将其添加到lstLibrary一次。在lstLibrary_SelectedIndexChanged()中,如果您实际在btnAdd_Click()中将书籍添加到集合中,则会更新集合中第一本书的文本框,该书籍不与所选书籍匹配。