繁体   English   中英

从asp.net中的自定义用户控件获取价值

[英]Getting value from a custom user control in asp.net

在完成这篇文章之前,我可能会回答自己的问题,但是如果我在这里遇到的问题失败了。

我需要从Club:ImageThumbnail控件中获取PhotoId值:

<asp:FormView ID="fvPhpto" runat="server" DataKeyNames="id"
     Width="480px" AllowPaging="True"
     PagerSettings-Visible="false">
     <ItemTemplate>
       <asp:Label Text='<%# Eval("title") %>' runat="server" ID="descriptionLabel" />
       <Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("id") %>' />
     </ItemTemplate>
     ...

这种事情int id = (int)fvPhpto.FindControl("thumb1").PhotoID; 无法使用,因为智能识别不会显示PhotoID。

这是Club:ImageThumbnail的代码如下所示:

public object PhotoID
{
    get
    {
        object o = ViewState["PhotoID"];
        return (o != null) ? (int)o : 0;
    }
    set
    {
        ViewState["PhotoID"] = (value != null && value !=DBNull.Value) ? Convert.ToInt32(value) : 0;     
    }
}

public ImageSizes ImageSize
{
    get
    {
        object o = ViewState["ImageSize"];
        return (o != null) ? (ImageSizes)o : ImageSizes.Thumb;
    }
    set
    {
        ViewState["ImageSize"] = value;
    }
}

public enum ImageSizes
{
    Large = 0,
    Thumb = 1,
    FullSize = 2
}

public string NoPhotoImg
{
    get
    {
        object o = ViewState["NoPhotoImg"];
        return (o != null) ? (string)o : null;
    }
    set
    {
        ViewState["NoPhotoImg"] = value;
    }
}

protected void Page_PreRender(object sender, System.EventArgs e)
{
    if (Convert.ToInt32(PhotoID) == 0)
    {
        if (NoPhotoImg != null)
        {
            Image1.ImageUrl = NoPhotoImg;
        }
        else
        {
            Image1.Visible = false;
        }
    }
    else
    {
        Image1.ImageUrl = "ImageFetch.ashx?Size=" + Convert.ToInt32(ImageSize) + "&ImageID=" + Convert.ToString(PhotoID);
    }
}


<asp:Image ID="Image1" runat="server" CssClass="photo" BorderWidth="1" />

您需要先强制转换为用户控件类型,然后intint以获取照片ID值,如下所示:

int id = (int)(fvPhpto.FindControl("thumb1") as ImageThumbnail).PhotoID;

如果将强制转换分为两个步骤,首先是用户控件类型,然后强制转换为int ,则可能更容易理解,这就像下面这样:

ImageThumbnail theUserControl = fvPhpto.FindControl("thumb1") as ImageThumbnail;

// Since the C# as operator returns null for a failed cast, then we need to 
// check that we actually have an object before we try to use it
if(theUserControl != null)
{
    int id = (int)theUserControl.PhotoID;
}

注意:如果ImageThumbnail不是用户控件的类名称,则将ImageThumbnail更改为用户控件的类名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM