0
在我的程序中,我需要添加一个插入类别的函数。我正在使用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;
}