ASP.NET UserControl输入参数

时间:2012-09-13 13:02:19

标签: asp.net user-controls

我已经写了这样的第一个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;
        }
    }

1 个答案:

答案 0 :(得分:0)

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