Introduction
I was working on a user control where I was trying to pass values from the pop user control to the parent page. It was very easy to use JavaScript and pass the value to the parent page, but it was not easy to find a way to pass value to the parent page without JavaScript. I did find a way to do this and want other developers to get some idea.
Background
Pass value between the user control and ASPX page without the help of JavaScript.
Using the Code
- Create a web project
- Add a user control to the project
- Next, see the code block
- Add these lines of code:
private DataSet data;
public delegate void U_ListCommandEventHandler
(object sender, U_ListCommandEventArgs e);
public event U_ListCommandEventHandler UGridViewChanged;
public int SelectedIndex
{
get { return UGridView.SelectedIndex; }
set
{
if (!Page.IsPostBack)
{
GVData_Bind();
}
if (value < UGridView.Rows.Count)
{
UGridView.SelectedIndex = value;
data = U_DataSet
(UGridView.Rows[UGridView.SelectedIndex].Cells[1].Text);
OnUGridViewChanged(new U_ListCommandEventArgs(data));
}
}
}
private DataSet GVData_Bind()
{
SqlConnection Con = new SqlConnection(Cn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT * FROM Person", Con);
data = new DataSet();
adapter.Fill(data, "U_Table");
return data;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
data= GVData_Bind();
UGridView.DataSource = data;
UGridView.DataBind();
}
}
private DataSet U_DataSet(string id)
{
SqlConnection Con = new SqlConnection(Cn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand
("SELECT * FROM Person where Id='" + id + "'", Con);
data = new DataSet();
adapter.Fill(data, "U_Table");
return data;
}
protected void UGridView_SelectedIndexChanged(object sender, EventArgs e)
{
data = U_DataSet(UGridView.Rows[UGridView.SelectedIndex].Cells[1].Text);
OnUGridViewChanged(new U_ListCommandEventArgs(data));
}
protected virtual void OnUGridViewChanged(U_ListCommandEventArgs e)
{
if (UGridViewChanged != null) UGridViewChanged(this, e);
}
public class U_ListCommandEventArgs
{
private DataSet _U_DataSet;
public U_ListCommandEventArgs(DataSet U_DataSet)
{
_U_DataSet = U_DataSet;
}
public DataSet U_DataSet { get { return _U_DataSet; } }
}
public class U_ListCommandEventHandler
{
public U_ListCommandEventHandler()
{
}
}
- Drag and drop the newly built user control on the ASPX page.
- Add or update the
OnInit()
method
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
GridViewUsercontrol1.UGridViewChanged+=
new GridViewUsercontrol.U_ListCommandEventHandler
(GridViewUsercontrol1_UGridViewChanged);
}
private void GridViewUsercontrol1_UGridViewChanged
(object sender, U_ListCommandEventArgs e)
{
GridView1.DataSource = e.U_DataSet;
GridView1.DataBind();
}
History
- 23rd February, 2008: Initial post