简体   繁体   中英

Accessing value from the controls within a dynamically loaded web user control (asp.net c#)

I have created a web user control (MemberDetails.ascx) which is loaded dynamically on a page (Member.aspx) for my website. The control has some TextBoxes. I want to store the values inputted by a user in these TextBoxes to a database on the click event of a button that is on the Member.aspx page (ie not a part of user control).

I'll use a small code for example.

Member.ascx page:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MemberDetails.ascx.cs" Inherits="Users_MemberDetails" %>
<div align="center">
<table runat="server" align="center" bordercolor="Black" id="tbl1">
<tr>
<td>First Name:</td><td><asp:TextBox ID="txtFname" runat="server" /></td>
</tr>
   <tr>
   <td>Last Name:</td><td><asp:TextBox ID="txtLname" runat="server" /></td>
   </tr>
</table>
</div>

Member.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Users_Booking : System.Web.UI.Page
{

 protected void Page_Load(object sender, EventArgs e)
 {
    UserControl Memberuc;
    Memberuc = (UserControl)LoadControl("MemberDetails.ascx");
    Memberuc.ID = "Memberuc1";
    PlaceHolder1.Controls.Add(Memberuc);
 }
 protected void btnSave_Click(object sender, EventArgs e)
 {
   /*Code for saving the input to a database*/
 }
}

I have tried several methods (using properties and FindControl etc.) to do it using suggestions on various forums, but nothing worked for me. Please post the required code. Thanks.

As the control will load its own viewstate, you could probably push the logic for the call to your DAL in your control:

public interface IMyUserControl
{
  void Save();
}

public class MemberDetails : UserConntrol, IMyUserControl
{
  // Other stuff here.

  public void Save()
  {
    string forename = txtFname.Text;
    string surname = txtLname.Text;

    // Call your DAL here.
  }
}

And then call it from your page:

protected void btnSave_Click(object sender, EventArgs e)
{
  var control = PlaceHolder1.FindControl("Memberuc1") as IMyUserControl;
  if (control != null)
  {
    control.Save();
  }
}

Thats all untested, but should point you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM