我正在尝试使用winforms进行预订系统。我有一个组合框,您可以从中选择一到十个数字。我也有10个组合框,我只希望显示的组框数量等于组合框中的选定数字。在组合框中,我有另一个组合框,我可以在其中选择座位编号,这就是为什么重要的是不能同时显示所有框。我有点失落,我曾试图使用动作玩家,但我没有成功。
这里我称之为组合框的GUI:
private void btnMakeBook_Click(object sender, EventArgs e)
{
ServiceReferenceBooking.BookingServiceClient bookingService = new ServiceReferenceBooking.BookingServiceClient();
ServiceReferenceTickets.TicketsServiceClient ticketsService = new ServiceReferenceTickets.TicketsServiceClient();
splitContainer1.Panel2.Controls.Clear();
InitializeMakeBookingComponents();
var allBookings = bookingService.GetAllBookings();
dataGridView2.DataSource = allBookings;
cbTickets.ValueMember = "amount";
cbTickets.DisplayMember = "amount";
cbTickets.DataSource = ticketsService.GetAllTickets();
}
这是我想要制作的活动:
private void cbTickets_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbTickets.SelectedItem.ToString() == "2")
{
gboxSeat2.Visible = true;
}
}
我收到错误:对象引用未设置为对象的实例。 它位于if语句所在的行上。
这是我尝试创建的事件,但选择2时GroupBox未显示。
希望你们能帮忙!感谢
答案 0 :(得分:0)
SelectedIndex
和SelectedItem
之间存在差异,第一个是所选项目的基于0的索引,第二个是您要查找的实际项目。试试这个
private void cbTickets_SelectedIndexChanged(object sender, EventArgs e)
{
if (((ComboBox)sender).SelectedItem == "2")
{
gboxSeat2.Visible = true;
}
}
充实我的建议:
public partial class Form1 : Form
{
//Declare your basic controls here
GroupBox gboxSeat1 = new GroupBox() { BackColor = Color.Red, Visible=false};
GroupBox gboxSeat2 = new GroupBox() { BackColor = Color.Blue, Visible = false };
GroupBox gboxSeat3 = new GroupBox() { BackColor = Color.Green, Visible = false };
GroupBox gboxSeat4 = new GroupBox() { BackColor = Color.Orange, Visible = false };
ComboBox cbTickets = new ComboBox() { Items = { "0", "1", "2", "3", "4" }, Height = 35, Width = 150 };
public Form1()
{
InitializeComponent();
//Setup handlers and add them to the panel
cbTickets.SelectedIndexChanged += comboBox2_SelectedIndexChanged;
panel1.Controls.Add(gboxSeat1);
panel1.Controls.Add(gboxSeat2);
panel1.Controls.Add(gboxSeat3);
panel1.Controls.Add(gboxSeat4);
panel1.Controls.Add(cbTickets);
}
private void InitializeBookingComponents()
{
//Arrange your controls the way you want here
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (((ComboBox)sender).SelectedItem == "2")
gboxSeat2.Visible = true;
}
}
这将确保您只有一个控件,您可以在闲暇时将其移除或添加到面板中,只保留一个控件