1

我已经像这样编写了我的第一个 UserControl:

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;
        }
    }
4

1 回答 1

0

是的,Page_Load为时过早 - 值不可用。要么覆盖该DataBind方法并将代码放在那里(我的第一选择),要么覆盖该OnPreRender方法并将其放在那里。

于 2012-09-13T13:43:52.277 回答