这是我到目前为止所拥有的。两班宾客和礼物。当用户将其输入到textBox时,Guest返回一个简单的名称。礼品是客人可以选择购买的商品清单。当用户提交他们的选择并输入他们的名字时,它将从第一个列表框中删除该项目,然后将所选项目+用户名称添加到第二个listBox。我似乎无法弄清楚为什么我的ToString()方法无法正常工作才能做到这一点。有什么建议吗?
我再次尝试将输入传递给我的类方法,然后获取该输出并将其放入第二个listBox。我可以轻松地使用输入的文本和选择的项目并将其移动,但这不会合并我的类。
这是我的表格:
public partial class Form1 : Form
{
//Guest newGuest = new Guest();
Guests newGuest = new Guests();
public Form1()
{
InitializeComponent();
}
List<Gift> newGift = new List<Gift>
{
new Gift("Horse"),
new Gift("Pony"),
new Gift("Plane"),
new Gift("Kite"),
new Gift("Lamp"),
new Gift("Dog"),
new Gift("Cat")
};
private void TextboxClear()
{
firstTxt.Clear();
}
//Method that adds choice from first listbox to second and removes it from the first
private void MoveListBoxItems(ListBox wishLst, ListBox takenLst)
{
ListBox.SelectedObjectCollection sourceItems = wishLst.SelectedItems;
foreach (var newGift in sourceItems)
{
takenLst.Items.Add(string.Format("{0}, {1}", newGift.ToString(), newGuest.ToString()));
TextboxClear();
}
while (wishLst.SelectedItems.Count > 0)
{
wishLst.Items.Remove(wishLst.SelectedItems[0]);
}
}
private void submitBtn_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(firstTxt.Text))
{
MessageBox.Show("Please enter first and last name.", "Warning");
this.DialogResult = DialogResult.None;
}
else
{
if (wishLst.SelectedIndex >= 0)
{
MoveListBoxItems(wishLst, takenLst);
}
else
{
return;
}
}
}
private void fillBtn_Click(object sender, EventArgs e)
{
wishLst.Items.Clear();
foreach (var item in newGift)
{
wishLst.Items.Add(item.ListGift);
}
}
}
}
嘉宾班:
class Guests
{
#region [ Fields ]
private string _name;
#endregion
#region [ Properties ]
public string Name
{
get { return _name; }
set
{
if (value == null)
throw new ArgumentNullException("Name",
"Name must not be null");
_name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value.Trim());
}
}
#endregion
#region [ Constructors ]
public Guests()
{
this.Name = string.Empty;
}
public Guests(string name)
{
this.Name = name;
}
#endregion
#region [ Methods ]
public override string ToString()
{
return String.Format("{0}",
this.Name.ToString());
}
#endregion
}
}
礼品类:
class Gift
{
private string _listGift;
public string ListGift
{
get { return _listGift; }
set { _listGift = value; }
}
public Gift()
{
this.ListGift = string.Empty;
}
public Gift(string listGift)
{
this.ListGift = listGift;
}
public override string ToString()
{
return string.Format("{0} Purchased by", this.ListGift);
}
}
}