在我的程序中,我需要添加一个add函数来插入类别。我正在使用treeView来显示数据。
How can I model this class in a database?
用户插入关卡,程序必须在该关卡中插入该类别。但我累了。因为它需要检查其他级别是否存在(IE:TreeView为空,我想添加2.1,所以这是一个错误)。
有时,您可以添加已设置的级别,因此必须禁止。
我的代码需要一些帮助。它已经完成,但我想改进它或修复错误(如果是这样)。
以下是代码:
private void AddButton_Click(object sender, RoutedEventArgs e)
{
NorthwindDataContext cd = new NorthwindDataContext();
int[] levels = LevelTextBox.Text.ToIntArray('.');
string newName = NameTextBox.Text;
int[] parentLevels = new int[levels.Length - 1];
Array.Copy(levels, parentLevels, parentLevels.Length);
Objective current = GetNode(levels);
Objective parent = GetNode(parentLevels);
if (current != null)
{
MessageBox.Show("Level already exists");
return;
}
else if (parent == null && parentLevels.Length != 0)
{
MessageBox.Show("Parent level doesn't exist");
return;
}
var newObjective = new Objective();
newObjective.Name = newName;
newObjective.Level = levels.Last();
newObjective.Parent_ObjectiveID = parent == null ? null : (int?)parent.ObjectiveID;
cd.Objective.InsertOnSubmit(newObjective);
cd.SubmitChanges();
MessageBox.Show("The new objective has added successfully");
NameTextBox.Clear();
LoadObjectives();
}
public Objective GetNode(params int[] indexes)
{
return GetNode(null, 0, indexes);
}
public Objective GetNode(int? parentid, int level, params int[] indexes)
{
NorthwindDataContext cd = new NorthwindDataContext();
Objective item = null;
if (indexes.Length == 0)
return null;
if (parentid == null)
{
item = (from p in cd.Objective
where p.Level == indexes[level] && p.Parent_ObjectiveID == null
select p).SingleOrDefault();
}
else
{
item = (from p in cd.Objective
where p.Level == indexes[level] && p.Parent_ObjectiveID == parentid
select p).SingleOrDefault();
}
if (item == null)
return null;
if (++level < indexes.Length)
item = GetNode(item.ObjectiveID, level, indexes);
return item;
}
答案 0 :(得分:1)
为什么不让用户选择应添加新类别的父节点?您可以让他们只需单击父节点,然后向其添加新节点。不涉及检查。我知道这不能解答您的直接问题,但您当前的方法对您和您的用户来说很难。