在GridView中添加TreeView窗体以填充ComboBox集合



我在Windows窗体应用程序中遇到以下问题。我有两个表单:内部有TreeView的CategoryTree.cs表单和内部有DataGridView的ProjectForm.cs表单。我想用TreeView节点文本填充DataGridViewComboBoxColumn集合。例如,我有一个树,看起来像这样:

Science Fiction 
   Movie1
   Movie2 
Horror 
   Movie1
   Movie2
Action
   Movie1
   Movie2

等等。我希望这些类别是ComboBoxColumn中的项目。我的代码在类别树形式中如下所示

public partial class CategoryTree : Form
{
   //adding nodes to the tree
   private void button2_Click(object sender, EventArgs e)
   {
      TreeNode newone = new TreeNode();
      newone.ForeColor = Color.Orange;
      newone.NodeFont = new Font(catTreeView.Font, FontStyle.Bold);
      newone.Text = nameBox.Text;
      catTreeView.Nodes.Add(newone);
      //and code for adding child and grandchild and ...
   }
   //other stuff 
}

在DataGridView中,我有以下方法

public void AddComboBox()
    {
        int i;
        CategoryTree cat_Form = new CategoryTree();
        //Set the cat_Form Active
        cat_Form = ActiveForm as CategoryTree;
        if (cat_Form != null)
        {
            i = cat_Form.catTreeView.Nodes.Count;  //here i get exception
            if(i != 0)
            {
                var newone2 = new DataGridViewComboBoxColumn();
                newone2.HeaderText = "Main category";
                newone2.Name = "ColNr_" + nofCols;
                string comboTxt;
                for(int j=0; j<i; j++){
                comboTxt = catTreeView.Nodes[j].Text;
                newone2.Items.Add(comboTxt);
                }
                mainProjectGrid.Columns.Add(newone2);
                nofCols += 1;
            }
        }
    }

不幸的是,此代码生成"System.NullReferenceException"。catTreeView修饰符设置为"public"。我对这个问题有很多不同的方法,但都不起作用。

正如你可能看到的那样,我的问题是——我如何从ProjectForm窗体中访问catTreeView对象并填充组合框?

我是一个绝对的初学者,所以使用示例代码的答案将永远受到赞赏。

致相关人员。我找到了这个问题的解决办法。在TreeView中,我添加了一个以这种方式编程的按钮

private void applyBtn_Click(object sender, EventArgs e)
{
    ProjectForm newProject1 = new ProjectForm( catTreeView );
    newProject1.MdiParent = this.ParentForm;
    newProject1.Text = "blabla";
    newProject1.Show();
}

接下来,我将其添加到ProjectForm.cs 中

public ProjectForm(TreeView catView)
{
    InitializeComponent();
    holalala = catView;
}
public void AddComboBox()
{
    int i;
    if (holalala != null)
    {
        i = holalala.Nodes.Count;
        if (i != 0)
        {
            var newone2 = new DataGridViewComboBoxColumn();
            newone2.HeaderText = "Main category";
            newone2.Name = "ColNr_" + nofCols;
            string comboTxt;
            for (int j = 0; j < i; j++)
            {
                comboTxt = holalala.Nodes[j].Text;
                newone2.Items.Add(comboTxt);
            }
            mainProjectGrid.Columns.Add(newone2);
            nofCols += 1;
        }
     }
}

这个解决方案非常简单,效果很好。我想我现在可以添加几行,不仅可以添加列,还可以用TreeView中可能出现的新节点更新它们。我稍后会处理:)。

最新更新