User6667769 User6667769 - 20 minutes ago 2
C# Question

can't able to add value to textbox

I have a datacontrol.cs(UserControl), which is contain textbox1 and codebehind window having a method with parameter of currentvalue

public void bindvalue(float currentvalue)
{
textbox1.Clear();
textbox1.Text = currentvalue.ToString();
}


I have a Form, Here added the usercontrol in this form and which contains a Button

So when clicking button it pass a currentvalue by the way of method to the datacontrol class like that .

private void button_click(object sender, EventArgs e)
{

float currentvalue = 1500.00f;
datacontrol obj = new datacontrol();

obj.bindvalue(currentvalue);
}


Everything working fine to me. It pass the current value to the usercontrol class and there current value assigned/added to the
textbox1.Text = currentvalue.ToString();
. It doesn't shows any error . But finally the textbox doesn't shows any value.

I used breakpoint to check the functionality. It gave current value to the textbox. But strange!!!..
I can't predict whats wrong in my code.
Helps appreciated.:)

Answer

Your instance of datacontrol with required value (1500.00f) does not exist on your form. You are only delcaring it, passing value and forgetting about it.

If you have already added user control to form and want to call bindvalue method of existing control, you should do the following:

private void button_click(object sender, EventArgs e)
{
    float currentvalue = 1500.00f;
    this.dataControl1.bindvalue(currentvalue);
}

Note that dataControl1 is the name of your user control on the form, it can be different from dataControl1.

If you want to create new user control and call bindvalue, you should add new instance on the form:

private void button_click(object sender, EventArgs e)
{
    float currentvalue = 1500.00f;
    datacontrol  obj = new datacontrol();

    obj.bindvalue(currentvalue);
    this.Controls.Add(obj);
}

If it is already dynamically added control on the form, declare a field of Form class, assign new instance of it control, when you want it, and call to it as it shows in the first example.