RP wrote:
[...]
The value of TotalRecords being shown is 0 whereas, I assigned it
value 10. Why it is becoming 0?
It's not "becoming" 0. You aren't using the same instance of the class.
In the instance in which you retrieve it, the value was never set, and
so it still has the original default value of 0.
And likewise, the instance in which you set it lived only long enough
for you to set it; at some point shortly after you set the value, the
garbage collector came along and released the instance in which you set
the value, because no one was referring to it any longer.
It sounds as though you are looking for some sort of "global variables"
class. Keeping in mind, of course, that it is generally better to have
data associated with some specific class rather than a general-purpose
"global variables" class, let's assume the desired behavior is reasonable.
Then what you probably want is for the class to actually just be a
static class. Declare the class and all of its members to be static,
then rather than instantiating the class, you'll just refer to it by the
type name. For example:
static class Global
{
static public int TotalRecords = 0;
}
(the initialization is superfluous, since 0 is the default for int
anyway, but whatever...)
Then elsewhere:
private void SaveRecord()
{
Global.TotalRecords = 10;
// etc...
}
private void LeaveRecordForm_Load(object sender, EventArgs e)
{
textBox1.Text = Global.TotalRecords.ToString();
}
Now, all that said, I would revisit my previous comment about avoiding
globals. They aren't in and of themselves terrible, but they are often
misused and, frankly, the short snippet of code you've provided here
seems to possibly be such a case. Two forms should not be using a
global variable to communicate with each other, IMHO. It is likely that
it would be better for the LeaveRecordForm constructor to take the value
as a parameter, or for the LeaveRecordForm class to expose a property
that the other Form can set, or for the other Form to expose the value
as a property and pass a reference to that Form instance to the
LeaveRecordForm (again, either in the constructor or a public property).
But if you really want a global variable, the above is one way to do it.
Pete