如何在ASP.NET C#中的用户控件之间传递值

我的页面中有3个用户控件。 其中一个用户控件是关于fileUploading,第二个是关于fileUploade关键字。 当文件上传时,fileUploading usercontrol返回记录该插入的Id。 现在我想在fileUploaded关键字中使用此id,但是当插入标签以查看fileuploading中的id时,用户控件显示右侧id例如1或2或..但是在关键字usercontrol中仅显示0值。 我使用entity framework工作。 如何在关键字用户控件中访问此ID。 谢谢。

您可以使用委托将id传递回父页面。 当id传递回父页面时,您在父页面上运行一个函数,该函数调用关键字usercontrol上的公共函数。

因此,在您的上传用户控件上,首先创建父页面将侦听的委托:

public delegate void PassIDToParent(string ID); public event PassIDToParent PassID; 

接下来,一旦返回id,就触发委托:

 protected void Upload() //--- this is your current upload function { //--- other upload code string ReturnedID = "1"; //--- whatever is returned PassID(ReturnedID); } 

现在,您需要在父页面上设置侦听器。 一旦监听器执行,它将执行“PassID”function。 在此函数中,您将调用关键字usercontrol的公共函数“LoadID”。 所以在父页面上,执行以下操作:

 protected void Page_Load(object sender, EventArgs e) { //--- setup the listener to receive the uploaded id UploadUserControlID.PassID += new UploadUserControlID_ClassName.PassIDToParent(PassID); } protected void PassID(string id) { //--- this method is called from the listener above and it passes the id KeywordUserControlID.LoadID(id); } 

关键字usercontrol的代码如下所示:

 public void LoadID(string id) { //--- do whatever you need to with the id } 

以下是有关代表使用的更多信息: http : //webdeveloperpost.com/Articles/Return-value-from-user-control-in-ASP-NET-and-C-Sharp.aspx

希望有所帮助! 祝好运! 不要忘记标记为答案!

会话变量可能是最好的方法:

http://msdn.microsoft.com/en-us/library/ms178581.aspx