Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Refrencing a datagrid from a user control on a form 1

Status
Not open for further replies.

ggeorgiou01

Programmer
Apr 11, 2005
60
GB
Hi,

I am relativly new to windows application programming, as i have always been a web developer.

But i have encountered a problem. I have a form, and on my form i have a user control (in the user control i have a datagrid: OrderLinesDg)

What i want to be able to do is, from a textbox (which is on my form) i want to be able to place the contents into the datagrid. Is this possible ? How do i refrence an item in a user control, from my form ?
 
Change the "Modifier" property of OrderLinesDg in the user control to public or internal. After that, access it in the form class with "this.<user control name>.OrderLinesDg"

Marcel
 
Thanks MKuiper,

That works a treat. How would it work if i wanted to refrencing something from my form, in my user control ?
 
I have nearly fixed the issue. I have tried the following code:

Completion f;
f.OrderTc.EnabledEnabled = true;


but i get the error message:

Use of unassigned local variable 'f'

Does anybody now how to refrence, an item from my form, within my user control ?
 
Normally you can't access a form member in a user control, simply because a user control can be put on any form, even those which do not have the item you want to reference.

However, there is a way to do it:

Suppose there is a button called "myButton" on the form, which you want to access from your user control:


1. Add an interface to your project:
Code:
using <all the required stuff, including System.Windows.Forms>;
namespace <your namespace>;
{
  public interface IMyButton
  {
    Button MyButton { get };
  }
}

2. Let the form implement the interface
Code:
public class MyForm : Form, IMyButton
{
  public Button MyButton
  {
    get
    { return myButton; }
  }
  // rest of class MyForm
}

3. In the user control, check if the form implements IMyButton. If it does you can access myButton through the interface:

Code:
IMyButton myButtonForm = this.FindForm() as IMyButton;
if { myButtonForm != null )
{
  // do something with myButtonForm.MyButton
}
else
{
  // myButton is not available
}

Marcel
 
The UserControl is derived from the ContainerControl and you can access the form on which it is always by using the property ParentForm or the parent container:

Code:
Control ctlParent=MyUserControl.Parent;
Form frmParent = MyUserControl.ParentForm;
// Find the form that contains MyUserControl
Form frmParent = MyUserControl.FindForm();
obislavu

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top