如何设置字典值其他表单? [英] How Can I Set Dictionary Value On Other Form?

查看:184
本文介绍了如何设置字典值其他表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#初学者,我下面遇到了问题,但我不知道是什么原因造成或如何解决它。经验的程序员,请帮助。



我有一个词典在Form1上,但我想设置从窗体2的值。然而,将数值之后,的MessageBox 结果仍显示0;



Form1中:MSGBOX显示结果为0

 公共Form1中()
{
的InitializeComponent();
bidcoords [测试] = 0;
}

公众解释<字符串,整数> bidcoords =新词典<字符串,整数>();

私人无效button2_Click(对象发件人,EventArgs五)
{
MessageBox.Show(bidcoords [TEST] Value.ToString());
}



窗体2:

  Form1中Form1中=新Form1的(); 

私人无效button2_Click(对象发件人,EventArgs五)
{
form1.bidcoords [TEST] = 30;
}


解决方案

在你的程序的一些点要创建窗体2 ,并将其显示。在那个时间点你是在 Form1中的 。这 Form1中,同样一个你可以在屏幕上看到的,是你要更新的形式。如果您尝试创建另一个 Form1中使用,你将不得不为两个 Form1中的情况下,这是不是你想要的。



您需要 Form1中和窗体2 Form1中的实例。



有两种常见的方法来这样做:




  1. 名为属性的MainForm 加入窗体2 。创建窗体2 ,设置 form2.MainForm =在此之后;

  2. 添加构造函数窗体2 ,需要一个表格作为参数,并保存离开



在这两种情况下,那么当你在窗体2 ,使用该变量来设置字典。


I am a C# beginner, I've encountered a problem as below, but I'm not sure what is causing it or how to fix it. Experience coders, please help.

I have a Dictionary in Form1, but I want to set its value from Form2. However, after assigning the value, the MessageBox result still shows 0;

Form1: msgbox show result = 0

    public Form1()
    {
        InitializeComponent();
        bidcoords["TEST"] = 0;
    }

    public Dictionary<string, int> bidcoords = new Dictionary<string, int>();

    private void button2_Click(object sender, EventArgs e)
    {
        MessageBox.Show(bidcoords["TEST"].Value.ToString());
    }

Form2:

    Form1 form1 = new Form1();

    private void button2_Click(object sender, EventArgs e)
    {
       form1.bidcoords["TEST"] = 30; 
    }

解决方案

At some point in your program you are creating Form2 and showing it. At that point in time you are in Form1. That Form1, the same one you can see on the screen, is the form you are trying to update. If you try to create another Form1 using new, all you will have is two Form1 instances, which is not what you want.

You need to communicate between Form1 and Form2 that instance of Form1.

There are two common approaches to doing this:

  1. Add a property called MainForm to Form2. After you create Form2, set form2.MainForm = this;
  2. Add a constructor to Form2 that takes a Form as an argument and save that away

In either case, then when you are in Form2, use that variable to set the dictionary.

这篇关于如何设置字典值其他表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆