خوب همون سناریوی تعریف Event که اول گفتم برای این نیاز پاسخگو هست.برای ارائه DataTable به فرم، یک راه تعریف یک Property در UserControl هست:
public Form1 : Form
{
public Form1()
{
InitializeComponents();
userControl11.SomeButtonClicked += new EventHandler(userControl11_someButtonClicked); // Subscribe
}
private userControl11_someButtonClicked(object sender, EventArgs e)
{
DataTable data = userControl11.Data;
// Do whatever with data...
}
}
public UserControl1: UserControl
{
public event EventHandler SomeButtonClicked;
private DataTable data;
public UserControl1()
{
InitializeComponents();
this.SomeButton.Click += new EventHandler(someButton_Click);
}
private userControl11_someButtonClick(object sender, EventArgs e)
{
// Do caluclations
// ...
this.data = [Result Data Table];
if (this.SomeButtonClicked != null)
this.SomeButtonClicked(this, EventArgs.Empty);
}
public DataTable Data
{
get { return this.data; }
}
}
و یا اگه DataTable مورد نظر مسقیما با رویداد در ارتباط میتونید اون رو به عنوان آرگومان رویداد به فرم ارسال کنید:
// Define event args
public SomeButtonClickedEventArgs : EventArgs
{
private DataTable data;
public SomeButtonClickedEventArgs(DataTable data)
{
this.data = data;
}
public DataTable Data
{
get { return this.data;}
}
}
// Define event handler
public delegate void SomeButtonClickedEventHandler(object sender, SomeButtonClickedEventArgs e);
//
public Form1 : Form
{
public Form1()
{
InitializeComponents();
userControl11.SomeButtonClicked += new SomeButtonClickedEventHandler(userControl11_someBu ttonClicked); // Subscribe
}
private userControl11_someButtonClicked(object sender, SomeButtonClickedEventArgs e)
{
DataTable data = e.Data;
// Do whatever with data...
}
}
public UserControl1: UserControl
{
public event SomeButtonClickedEventHandler SomeButtonClicked;
public UserControl1()
{
InitializeComponents();
this.SomeButton.Click += new EventHandler(someButton_Click);
}
private userControl11_someButtonClick(object sender, SomeButtonClickedEventArgs e)
{
// Do caluclations
// ...
DataTable data = [Result Data Table];
SomeButtonClickedEventArgs ea = new SomeButtonClickedEventArgs(data);
if (this.SomeButtonClicked != null)
this.SomeButtonClicked(this, ea);
}
}