如何在运行时改变gridview单元格的图像

本文关键字:单元格 图像 gridview 改变 运行时 | 更新日期: 2023-09-27 18:04:45

我有一个gridview,包含一个列名"历史",其中有加(+)图像按钮。单击加号图像按钮会在下面添加新行。插入新行应该只将该特定父行的加号图像按钮的图像更改为减号(-)图像按钮。其余行应该有加号图像按钮。

Q1。如何知道所选行的行索引,以便更改图像?

其次,如果我点击减号图像按钮,它应该重置为加号图像按钮,添加的子行不应该被看到。

Q2。如何将图像更改回加图像按钮?

我在gridview模板字段中添加了Plus图像按钮。因此,当网格被加载时,Plus图像是可见的。

请建议!

谢谢!

如何在运行时改变gridview单元格的图像

首先添加一个带有图像按钮的模板列:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Srl"
    DataSourceID="EntityDataSource1" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/Left.gif" CommandName="Add" />
            </ItemTemplate>
        </asp:TemplateField>
        <%--Other columns--%>
    </Columns>
</asp:GridView>

然后在GridView1_RowDataBound事件处理程序中设置按钮command参数为行索引:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton button = (ImageButton)e.Row.FindControl("ImageButton1");
            button.CommandArgument = e.Row.RowIndex.ToString();
        }
    }

最后在GridView1_RowCommand事件处理程序切换ImageButton imageUrl和CommandName,并做任何你想做的添加和删除行:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow selectedRow = GridView1.Rows[index];
        ImageButton button = (ImageButton)e.CommandSource;
        switch (e.CommandName)
        {
            case "Add":
                // Use selectedRow to add your rows       
                button.ImageUrl = "~/images/down.gif";
                button.CommandName = "Remove";
                break;
            case "Remove":
                // Use selectedRow to remove your rows
                button.ImageUrl = "~/images/left.gif";
                button.CommandName = "Add";
                break;
        }
    }