winforms: Bind int to a control

  • Thread starter Thread starter SteveK
  • Start date Start date
S

SteveK

I have a text box and I simply want to bind it to an int variable. I'm
testing how all this stuff works and I wanted to test if I increment the
int, will the textbox update automatically, however I didn't get far cause I
can't get binding to work with an int OR I should say it wants an object and
a member..

Any tips or heads-ups?

Thanks-
Steve
 
Steve,

You won't be able to do this. You will need an object that stores the
int, and exposes it as a property, also firing an event when it changes. An
int is a value type, and doesn't have any mechanism to indicate when the
value changes.

Your only choice would be to create an object with a property that
exposes this, and an event that fires (named correctly <property
name>Changed of type EventHandler) when the property changes.

Hope this helps.
 
Thanks Nicholas,

I switched over to just use a DataTable, I figure it's all built in and for
testing purposes it would be easier ;)

Thanks for the quick response though!.


Nicholas Paldino said:
Steve,

You won't be able to do this. You will need an object that stores the
int, and exposes it as a property, also firing an event when it changes. An
int is a value type, and doesn't have any mechanism to indicate when the
value changes.

Your only choice would be to create an object with a property that
exposes this, and an event that fires (named correctly <property
name>Changed of type EventHandler) when the property changes.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

SteveK said:
I have a text box and I simply want to bind it to an int variable. I'm
testing how all this stuff works and I wanted to test if I increment the
int, will the textbox update automatically, however I didn't get far cause
I
can't get binding to work with an int OR I should say it wants an object
and
a member..

Any tips or heads-ups?

Thanks-
Steve
 
Hi Steve,

You can bind it to a property that reflects an int

private int myint = 0;
public int Val
{
get { return myint; }
set { myint = value; }
}


textBox1.DataBindings.Add("Text", this, "Val");

This will initially update the textbox and any later changes to the textbox will be stored in the int. However, if you change the int internally it will not update the textbox. If you do that, you need to update the textbox by calling ReadValue on the databinding

textBox1.DataBindings["Text"].ReadValue();
 
Back
Top