日期:2014-05-18  浏览次数:20471 次

怎么为用户控件中的控件赋值?【有代码】
我的用户控件:Webnews.ascx如下
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebNews.ascx.cs" Inherits="WebNews" %>
<div class="WebNews">
  <asp:Literal ID="LiteralNews" runat="server" Text="pppppp" ></asp:Literal>
  <br />
  <asp:Label ID="LabelNews" runat="server" Text="haha"></asp:Label>
</div>

Webnews.ascx.cs如下
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class WebNews : System.Web.UI.UserControl
{
  protected void Page_Load(object sender, EventArgs e)
  {
   
  }
}

我的主页面:Default.aspx如下
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="WebNews.ascx" TagName="WebNews" TagPrefix="uc1" %>





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>无标题页</title>
</head>
<body>
  <form id="form1" runat="server" >
  <div >
  <uc1:WebNews ID="WebNews1" runat="server" />

   
  &nbsp;</div>
  </form>
</body>
</html>

Default.aspx.cs如下
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
  if (IsPostBack == false)
  {
   
  UserControl my = (UserControl)LoadControl("WebNews.ascx");
  Literal myliteral = my.FindControl("LiteralNews") as Literal;
  myliteral.Text = "just do it";
  my.Visible = true;
  }
  }
}
我单步调试的时候,发现myliteral.Text能够取到用户控件中的值,但是没法给它赋值。请问原因何在?希望各位高手指点一下。

------解决方案--------------------
在Webnews.ascx里写一个函数:
public void SetLiteralNewsValue(string value)
{
LiteralNews.Text = value;
LiteralNews.Visible = true; 
}

Default.aspx
if (IsPostBack == false) 


UserControl my = (UserControl)LoadControl("WebNews.ascx"); 
my.SetLiteralNewsValue("Just Do It!");


这样程序的结构也好些。
------解决方案--------------------
UserControl uc = (UserControl)LoadControl("~/WebNews.ascx");
Form.Controls.Add(uc);
Literal myliteral = uc.FindControl("Literal1") as Literal;
myliteral.Text = "just do it";

偶是5楼滴,刚刚有事去了。回来帮你解决一下。这个我测试通过了。