【问题标题】:How to create a Add function for a record database?如何为记录数据库创建添加功能?
【发布时间】:2011-08-17 21:14:45
【问题描述】:

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

【问题讨论】:

    标签: c# wpf linq linq-to-sql treeview


    【解决方案1】:

    为什么不让用户选择应该添加新类别的父节点?您可以让他们单击父节点,然后向其添加新节点。不涉及检查。我知道这并不能回答您的直接问题,但是您当前的方法对您您的用户来说很难。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 2015-08-03
      相关资源
      最近更新 更多