Reputation: 8302
I have a Datalist on my asp.net page with an ImageButton
in the <Item Template>
. When an ImageButton
is clicked, I use the ItemCommand
event to set the border of the data item:
protected void dlProducts_ItemCommand(object source, DataListCommandEventArgs e)
{
e.Item.BorderColor = System.Drawing.ColorTranslator.FromHtml("#ff5800");
e.Item.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffeee5");
}
That works fine, but the border disappears when a postback occurs. I've tried binding my datalist in the page load event like so:
if (!Page.IsPostBack)
{
dlProducts.DataSource = ObjectDataSource4;
dlProducts.DataKeyField = "Product_ID";
dlProducts.DataBind();
}
But the border is gone after a postback. What gives?
Here is the datalist markup:
<asp:DataList ID="dlProducts" runat="server" CellPadding="5" CellSpacing="5"
OnItemCommand="dlProducts_ItemCommand"
RepeatColumns="4" RepeatDirection="Horizontal"
ondatabinding="dlProducts_DataBinding"
onitemdatabound="dlProducts_ItemDataBound" >
<ItemTemplate>
<asp:ImageButton ID="img" ImageAlign="Middle" runat="server"
ImageUrl='<%# "~/uploads/profile/" + DataBinder.Eval(Container.DataItem,"ProfileImageName").ToString() %>'
onclick="img_Click" />
</ItemTemplate>
</asp:DataList><asp:ObjectDataSource ID="ObjectDataSource4" runat="server" SelectMethod="GetAllCompetitorProducts"
TypeName="DalProduct" OldValuesParameterFormatString="original_{0}">
<SelectParameters>
<asp:SessionParameter Name="producttype_id" SessionField="ProductType_id" Type="Int32" DefaultValue="13" />
<asp:SessionParameter DefaultValue="2009" Name="Year" SessionField="Year" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Upvotes: 0
Views: 1921
Reputation: 4809
Try this:
<ItemTemplate>
<div id="divImg" runat="server">
<asp:ImageButton ID="img" ImageAlign="Middle" runat="server"
ImageUrl='<%# "~/uploads/profile/" + DataBinder.Eval(Container.DataItem,"ProfileImageName").ToString() %>'
onclick="img_Click" />
</div>
</ItemTemplate>
In ItemCommand
protected void dlProducts_ItemCommand(object source, DataListCommandEventArgs e)
{
var divImg = (HtmlGenericControl)e.Item.FindControl("divImg");
divImg.Style.Add("background-color", "#ffeee5");
}
As you can see, img control is now wrapped in a server div element so that when postback occurs it automatically restores its state from viewstate. Being said that, it works fine with postback but if you rebind your grid, it would lose its style. For it to persist after the re-bind, on itemcommand store the id's of the img in viewstate and apply the style according.
Also, I would suggest using class attribute for div element instead of applying colors in code-behind.
divImg.Attributes.Add("class", "classnamewhichhasgroundandbordercolor");
Upvotes: 1