user3096551
user3096551

Reputation: 31

How to access hashtables value from another forms?

I have tree form and a hashtable.Hashtable was created in form1.How can i access hashtable values from form3.

f1.hash[txtUpNumber.Text] = " "+txtUpName.Text +"/"+ txtUpGrade.Text +"/"+ txtUpLGrade.Text;

I use this code and there is no mistake but hashtable values null.

    public Form2 f2;
    public Form1 f1;
    public Form3()
    {
        InitializeComponent();
    }

    private void Form3_Load(object sender, EventArgs e)
    {

     }
    public void disp(ListViewItem each)
    {
        txtUpNumber.Text = each.SubItems[0].Text;
        txtUpName.Text = each.SubItems[1].Text.TrimStart();
        txtUpGrade.Text = each.SubItems[2].Text;
        txtUpLGrade.Text = each.SubItems[3].Text;
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {   try
        {
        f1.hash[txtUpNumber.Text] = " "+txtUpName.Text +"/"+ txtUpGrade.Text +"/"+   txtUpLGrade.Text; //update hashtable
        this.Hide();
        Form2 f2 = new Form2();
        f2.ShowDialog();
        }catch(Exception ex)
        {
            MessageBox.Show(ex.ToString()); 
        }
    }

Firstly I fill data with listviewitems and I take information from textbox for hashtable. I dont see error but f1.hash is null? This is hashtable creation in form1.

public  Hashtable hash = new Hashtable();

Upvotes: 0

Views: 615

Answers (2)

Vadim
Vadim

Reputation: 2865

This is what happens -

  1. You have a dictionary defined in Form1
  2. It is initialized and you probably put values inside in a certain instance of Form1 with which you work.
  3. Your Form3 instance holds a reference to some (initialized or not) instance of Form1, but it is not the same instance.

So, you will have to pass a relevant reference to your Form3 and there are several ways you could do it -

  1. Pass a reference to the dictionary or to Form1 in the constructor of Form3.

    public Form3(Form1 p_form1)    
    {
        f1 = p_form1;
    }        
    
  2. Define the dictionary to be a static member of Form1. This will work and is very simple to do, but this is a bad design, for example it will not allow you to create several instances of Form1. Then you could simply access it like below and you don't need your f1 member variable

    Form1.hash[txtUpNumber.Text] = " "+txtUpName.Text +"/"+ txtUpGrade.Text +"/"+ txtUpLGrade.Text;
    
  3. You can also pass a Delegate that will look up the value you need in the dictionary in Form3 constructor.

  4. You can store the dictionary in someplace that is accessible to both forms, in some other class.

Upvotes: 1

Scott Yang
Scott Yang

Reputation: 567

I think your problem may be the proper way to pass value from another form, here is a reference for you: update selected row in datagridview from another form

Upvotes: 0

Related Questions