2012-09-13 65 views
1

我寫我的第一個用戶控件這樣的:ASP.NET用戶控件輸入參數

public partial class DefectMap : System.Web.UI.UserControl 
{ 
    const string imageProviderUrl = "~/DefectMapImageProvider.ashx?"; 

    public long MapID { get; set; } 
    public int Rows { get; set; } 
    public int Cols { get; set; } 
    public int? Width { get; set; } 
    public int? Height { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     ComposeImageUrl(); 
     GenerateTableStructure(); 
    } 

    void ComposeImageUrl() 
    { 
     StringBuilder builder = new StringBuilder(imageProviderUrl); 
     builder.AppendFormat("DefectMapId={0}", MapID); 

     // set up width & height 
     if (Width != null && Width > 0) 
     { 
      builder.AppendFormat("&Width={0}", Width); 
      MapImage.Width = (Unit)Width; 
     } 

     if (Height != null && Height > 0) 
     { 
      builder.AppendFormat("&Height={0}", Height); 
      MapImage.Height = (Unit)Height; 
     } 

     MapImage.ImageUrl = builder.ToString(); 
    } 

    void GenerateTableStructure() 
    { 
     if (Rows > 0 && Cols > 0) 
     { 
      TableHelper.CreateStructure(MapTable, Rows, Cols); 
     } 
    } 
} 

如果我加入一些網頁上,該控制設定值標記

<uc:DefectMap ID="DefectMap" runat="server" Height="80" MapID="1" /> 

它就像我期望。但是,如果我試圖在代碼中設置值(行,MapID等),它不起作用。你明白爲什麼不?我應該使用不同的方法(比Page_Load)來處理控制邏輯嗎?我用這個控件作爲GridView控件的孩子,試圖這樣:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     GridView grid = (GridView)sender; 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      DefectMap defectMap = (DefectMap)e.Row.FindControl("DefectMap"); 
      DEFECTMAP data = (DEFECTMAP)e.Row.DataItem; 

      defectMap.MapID = data.ID_DEFECTMAP; 
      defectMap.Rows = data.ROWS; 
      defectMap.Cols = data.COLS; 
     } 
    } 

回答

0

是,Page_Load太早 - 值是不可用的。重寫DataBind方法並將代碼放在那裏(我的第一選擇),或覆蓋OnPreRender方法並將其放在那裏。

+0

我發現與Page_Load類似的方法:Page_PreRender。惠特它,它的作品。謝謝。 – Fanda