我试图让用户能够将ingredient
添加到列表框中。
以下是相关课程的简要说明:
RecipeForm
就是表格。的集合管理器类
RecipeManager
是Recipe
的类
Recipe
是"内容"字段ingredients
为
ListManager
是经理类RecipeManager
继承自的通用基类。
我希望用户输入recipe
对象的成分。
然后将该对象保存在RecipeManager
类RecipeForm
的对象中。
集合中保存的Recipe
个对象列表(下面代码中为m_foodManager
)应该显示在RecipeForm
以下是我尝试的方法:
表单FoodRegister
:
public partial class FoodRegister : Form
{
private Recipe m_food = new Recipe();
private RecipeManager m_foodmanager = new RecipeManager();
public FoodRegister()
{
InitializeComponent();
}
private void ReadValues()
{
m_food.Ingredients.Add(Ingredienttxt.Text);
}
private void UpdateResults()
{
ResultListlst.Items.Clear(); //Erase current list
//Get one elemnet at a time from manager, and call its
//ToString method for info - send to listbox
for (int index = 0; index < m_foodmanager.Count; index++)
{
Recipe recipe = m_foodmanager.GetAt(index);
//Adds to the list.
ResultListlst.Items.Add(recipe);
ResultListlst.DisplayMember = "Ingredients";
}
}
private void Addbtn_Click(object sender, EventArgs e)
{
Recipe recept = new Recipe();
m_foodmanager.Add(recept);
ReadValues();
UpdateResults();
}
}
Recipe
上课
public class Recipe
{
private ListManager<string> m_ingredients = new ListManager<string>();
public ListManager<string> Ingredients
{
get { return m_ingredients; }
}
public override string ToString()
{
return string.Format("{0}", this.Ingredients);
}
}
RecipeManager
类(此类为空,因为它从ListManager
继承了它的方法。:
public class RecipeManager : ListManager<Recipe>
{
public RecipeManager()
{
}
}
ListManager
类:
public class ListManager<T> : IListManager<T>
{
protected List<T> m_list;
public ListManager()
{
m_list = new List<T>();
}
public int Count
{
get { return m_list.Count; }
}
public void Add(T aType)
{
m_list.Add(aType);
}
public void DeleteAt(int anIndex)
{
m_list.RemoveAt(anIndex);
}
public bool CheckIndex(int index)
{
return ((index >= 0) && (index < m_list.Count));
}
public T GetAt(int anIndex)
{
if (CheckIndex(anIndex))
return m_list[anIndex];
else
return default(T);
}
public override string ToString()
{
if(m_list != null && m_list.Any())
{
return string.Join(", ", m_list);
}
return string.Empty;
}
}
问题是列表框上没有显示任何内容,而是添加空字符串。我不确定我是否正确地将字符串添加到集合中。我希望用户通过向文本框中输入值来为集合添加字符串