就是这种情况。 我有一个库存更新功能:
public void UpdateInventoryList()
{
dgInventory.RowHeadersVisible = false;
dgInventory.ColumnCount = 2;
dgInventory.Columns[0].Name = "Name";
dgInventory.Columns[0].Width = 112;
dgInventory.Columns[1].Name = "Quantity";
dgInventory.Rows.Clear();
foreach (InventoryItem inventoryItem in _player.Inventory)
{
if (invetoryItem.Quantity > 0)
{
dgInventory.Rows.Add(new[] { inventoryItem.Details.Name, inventoryItem.Quantity.ToString() });
}
}
}
然后我为玩家宠物提供了一个ComboBox:
private void UpdatePet()
{
List<Pet> pets = new List<Pet>();
foreach (InventoryItem inventoryItem in _player.Inventory)
{
if (inventoryItem.Details is Pet)
{
if (inventoryItem.Quantity > 0)
{
pets.Add((Pet)inventoryItem.Details);
}
}
}
if (pets.Count == 0)
{
cboPet.Enabled = false;
btAttack.Enabled = false;
}
else
{
cboPet.DataSource = pets;
cboPet.DisplayMember = "Name";
cboPet.ValueMember = "ID";
cboPet.SelectedIndex = 0;
}
cboPet.SelectedIndexChanged += new System.EventHandler(cboPet_SelectedIndexChanged);
}
好了,现在我有一个功能,如果按下“SACRIFICE”按钮,它会从库存中删除Pets,然后在ComboBox中删除:
private void btSacrifice_Click(object sender, EventArgs e)
{
Pet currentpet = (Pet)cboPet.SelectedItem;
if (currentpet.Sacrificable == true && _player.CurrentHP < _player.MaxHP)
{
foreach (InventoryItem oi in _player.Inventory)
{
if (oi.Details.ID == currentpet.ID)
{
oi.Quantity--;
}
UpdateInventoryList();
}
if (_player.CurrentHP + currentpet.HealHP >= _player.MaxHP)
{
_player.CurrentHP = _player.MaxHP;
barHP.Value = _player.CurrentHP;
lblHp.Text = _player.CurrentHP.ToString();
btSacrifice.Enabled = false;
btCallPet.Enabled = false;
}
else
_player.CurrentHP = (_player.CurrentHP + currentpet.currentHP);
barHP.Value = _player.CurrentHP;
lblHp.Text = _player.CurrentHP.ToString();
btSacrifice.Enabled = false;
btCallPet.Enabled = false;
}
else if (!currentpet.Sacrificable == true)
{
tboxCombat.Text += "Not Sacrificable Pet!" + Environment.NewLine;
}
UpdateInventoryListI();
UpdatePet();
}
这一切都很完美,但如果我的库存中只有一只宠物,并且在我的组合框中确定它删除了宠物时,组合框被禁用并显示宠物的名称,在这种情况下我删除了宠物。如果我有一个以上的宠物,那么组合框就会启用(这没关系)并显示我拥有的另一只宠物。
为什么我在删除时仍然只有一只宠物(组合框中的“项目”)仍在将其名称重叠?
希望你能帮助和谢谢!
尤金
答案 0 :(得分:0)
这是因为当没有项目时,您的代码只会停用combobox
而不重置DataSource
:所以您需要添加cboPet.DataSource = null;
,如下所示:
if (pets.Count == 0)
{
cboPet.DataSource = null; //add this
cboPet.Enabled = false;
btAttack.Enabled = false;
}
else
{
cboPet.DataSource = pets;
cboPet.DisplayMember = "Name";
cboPet.ValueMember = "ID";
cboPet.SelectedIndex = 0;
}
另外,附注:你应该在课程级别定义List<Pet> pets
,这样你就不需要继续设置DataSource
。
第二个注意事项:您多次订阅cboPet.SelectedIndexChanged += new System.EventHandler(cboPet_SelectedIndexChanged);
,将其移出当前函数,或者在再次注册之前取消订阅。
答案 1 :(得分:0)
我认为你应该删除ComboBox
的选择:
if (pets.Count == 0)
{
cboPet.SelectedIndex = -1; //remove selection
cboPet.Enabled = false;
btAttack.Enabled = false;
}