active92
active92

Reputation: 654

Passing value from class to button click event

I would like to pass int _iD to my button click event. For now, I've passed my value to textbox and use it in button click. Is there anyway to bypass the textbox?

public MifarePasswordForm(int _iD)
{
    InitializeComponent();
    int iD = _iD;
    textBox1.Text += iD;
}

Button click event

private void btnOK_Click(object sender, EventArgs e)
{
    byte Oid = Convert.ToByte(textBox1.Text);
}

Upvotes: 1

Views: 1044

Answers (3)

DDave
DDave

Reputation: 618

Make a private property if both methods exist in single class else make public property and use it,

public int nID;

public MifarePasswordForm(int _iD)
{
    InitializeComponent();
    nID = _iD;
    textBox1.Text += iD;
}

Button click event

private void btnOK_Click(object sender, EventArgs e)
{
    byte Oid = Convert.ToByte(nID);
}

Upvotes: 1

Roman
Roman

Reputation: 12201

You should declare this variable as class level variable:

public class MifarePasswordForm
{
    public int iD {get;set;} // or private field

    public MifarePasswordForm(int _iD)
    {
        InitializeComponent();
        iD = _iD; // here you don't create, only use
        textBox1.Text += iD;
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
       //inside this method you can use this variable

       byte Oid = Convert.ToByte(iD);
    }

    //other code
}

Now you can use this variable in any method of this class.

Upvotes: 1

Ian
Ian

Reputation: 30823

What you currently do is to make your iD a local variable (that is, in the method/constructor scope):

public MifarePasswordForm(int _iD)
{
    InitializeComponent();
    int iD = _iD; //here it is, the iD is in the constructor/method scope, 
                  //it cannot be accessed outside of the scope
    textBox1.Text += iD;
}

You should make your iD a private field in the class scope rather than in the method scope:

private int iD; //declare here
public MifarePasswordForm(int _iD)
{
    InitializeComponent();
    iD = _iD; //don't declare here
    textBox1.Text += iD;
}

So that you can use it like this:

private void btnOK_Click(object sender, EventArgs e)
{
   byte Oid = (byte)iD;
 }

Upvotes: 1

Related Questions