我正在创建一个程序,该程序允许用户在6个单独的文本框中键入各种数据,然后将其保存到名为Book的对象中。现在,我已轻松完成此操作,但是现在,我希望能够在列表框中选择Book对象并将数据填充回文本框中,我认为这与将加法转换到一定程度一样容易,但是我已经点击了障碍。
这是我的上下文添加按钮的主要部分(我对其进行了评论,希望可以清除所有变量名)
//use class book to create a new book
Book addBook = new Book();
//use int.tryparse to convert the txtISBN to an int and store in the book object
bool parsed = int.TryParse(txtISBN.Text, out int isbn);
if (parsed)
{
addBook.gsISBN = isbn;
}
else
{
MessageBox.Show("Invalid ISBN, Please enter an integer value");
return;
}
//use double.tryparse to convert the txtPrice into a double and store in the book object
bool parse = double.TryParse(txtPrice.Text, out double price);
if (parsed)
{
addBook.gsPrice = price;
}
else
{
MessageBox.Show("Invalid Price, please enter a double value");
return;
}
//use object addBook with the various getters and setters for
//each variable and have them equal their textbox equivalent .
addBook.gsAuthor = txtAuthor.Text;
addBook.gsTitle = txtBookTitle.Text;
addBook.gsPublisher = txtPublisher.Text;
addBook.gsDate = txtDate.Text;
//myBooks( this is the Array)
myBooks[currentIndex] = addBook;
上面这段代码有效,但是下面的代码无效,这是我希望弄清楚的。
private void lstbook_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstbook.SelectedIndex == -1)//if there is no selected game output error message
{
MessageBox.Show("Please select a book");
}
else
{
int index = lstbook.SelectedIndex;
Book getBook = new Book();
myBooks[currentIndex] = getBook;
txtAuthor.Text = getBook.gsAuthor;
}
}
答案 0 :(得分:0)
是的,这很容易。假设您有书籍数组,将其分配给DataSource
Book[] books = //.... retrieve books here
lstBooks.DisplayMember = "Name"; // Book.Name
lstBooks.ValueMember = "Isbn"; // Book.Isbn, but it is don't matter for our logic
lstBooks.DataSource = books; // in this order, please
现在,请记住,您所有的书都在那里,您可以使用lst.SelectedItem
对其进行检索。因此,请在SelectedIndexChanged
上执行以下操作:
// clear text boxes here first
Book selectedBook = lstBooks.SelectedItem as Book;
if (selectedBook != null)
{
txtIsbn.Text = selectedBook.Isbn;
txtName.Text = selectedBook.Name;
}
else
MessageBox.Show("Please select a book");
这也可以使用BindingSource
来实现,您可以在其中绑定所有控件,而无需手动填充字段。