There can be scenarios, wherein you may have to collect data from various web parts in a page and submit to back end. One solution will be to use Connected Web parts feature. Or the sample code below also will help to achieve this;
1) Define one base class
public abstract class IBaseForm : WebPart
{
}
{
}
2) Implement this class in all the web parts whose data need to be collected
public class InputForm2 : IBaseForm
{
protected override void CreateChildControls()
{
base.CreateChildControls();
TextBox t1 = new TextBox();
t1.ID = "LastName";
t1.Text = "Last Name";
this.Controls.Add(t1);
}
}
{
protected override void CreateChildControls()
{
base.CreateChildControls();
TextBox t1 = new TextBox();
t1.ID = "LastName";
t1.Text = "Last Name";
this.Controls.Add(t1);
}
}
3) This is the piece of code which will collect the data from all the web parts which implement the base class
public class SubmitButton : WebPart
{
TextBox t1 = new TextBox();
protected override void CreateChildControls()
{
base.CreateChildControls();
Button b1 = new Button();
b1.ID = "submitData";
b1.Text = "Submit Data";
b1.Click += new EventHandler(b1_Click);
this.Controls.Add(b1);
t1.ID = "result";
this.Controls.Add(t1);
}
void b1_Click(object sender, EventArgs e)
{
t1.Text = string.Empty;
System.Web.UI.ControlCollection colls = this.Parent.Controls;
IEnumerable bf= colls.OfType();
foreach (IBaseForm f in bf)
{
t1.Text = t1.Text + GetValue(f);
}
}
string GetValue(IBaseForm f)
{
string res = string.Empty;
TextBox t = default(TextBox);
foreach (System.Web.UI.Control c in f.Controls)
{
if (c.GetType().Equals(typeof(TextBox)))
t = c as TextBox;
break;
}
res = t.Text;
return res;
}
}
{
TextBox t1 = new TextBox();
protected override void CreateChildControls()
{
base.CreateChildControls();
Button b1 = new Button();
b1.ID = "submitData";
b1.Text = "Submit Data";
b1.Click += new EventHandler(b1_Click);
this.Controls.Add(b1);
t1.ID = "result";
this.Controls.Add(t1);
}
void b1_Click(object sender, EventArgs e)
{
t1.Text = string.Empty;
System.Web.UI.ControlCollection colls = this.Parent.Controls;
IEnumerable
foreach (IBaseForm f in bf)
{
t1.Text = t1.Text + GetValue(f);
}
}
string GetValue(IBaseForm f)
{
string res = string.Empty;
TextBox t = default(TextBox);
foreach (System.Web.UI.Control c in f.Controls)
{
if (c.GetType().Equals(typeof(TextBox)))
t = c as TextBox;
break;
}
res = t.Text;
return res;
}
}
No comments:
Post a Comment