在 GridView 中设置用户控件对象属性 ASP.NET

Set User Controls Objects Properties inside a GridView ASP.NET

我在 gridview 中插入了三个模板列。在每一列中,我都插入了一个用户控件。例如,在第一列中有一个包含图像和三个标签的用户控件。

在我的页面加载过程中,我需要获取文件夹中的图像列表并为每个图像创建一行。然后我需要更新 gridview 列中那些用户控件的图像。

下面是获取图像列表的示例代码,将作为 GridView 的数据源:

        string[] filePaths = Directory.GetFiles(Server.MapPath("~/Resources/Pictures"));
        GridView1.DataSource = filePaths;
        GridView1.DataBind();

在这一步中,我可以看到 4 行填充了 RAW 用户控件(图像控件中的空图像、标签的默认文本等)。现在我需要用我自己的属性更新它们中的每一个。

这是我输出的图片:

正如您在第一列中看到的那样,有一些控件(图像和标签)用于我在 gridview 的列模板中使用的用户控件。但它们是 RAW,我需要更新它们。例如,我需要使用您在第三列中看到的 link 更新图像。

这是我的 GridView 代码的一部分:

<asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" Caption="Image List" CellPadding="2" ForeColor="Black" GridLines="None" Height="222px" Width="409px">
    <AlternatingRowStyle BackColor="PaleGoldenrod" />
    <Columns>
        <asp:TemplateField HeaderText="Old Picture">
            <ItemTemplate>
                <uc1:ImageColumn ID="ImageColumn1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="New Picture">
            <ItemTemplate>
                <uc2:ReplaceColumn ID="ReplaceColumn1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Allow Access">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

希望已经足够清楚了。有人可以帮忙吗?

您必须向您的用户控件添加 public 属性,然后使用 "normal" 数据绑定表达式对其进行设置。例如:

用户控制:

public class MyUserControl : UserControl
{
    public string ImageName {get; set;}
}

网格的模板列:

<asp:TemplateField ...>
    <ItemTemplate>
        <uc1:MyUserControl runat="server" ImageName='<%# Eval("ImageUrl")%>' ... />

代码隐藏:

public class ImageVM { // view-model for data-binding
    public string ImageUrl { get; set; }
}

...

var images = LoadImages(); // returns a list of ImageVM instances
grid.DataSource = images;
grid.DataBind();