I have a datalist that is populated using an ArrayList. When this is rendered i want to set the background image depending on a list item value, at the moment i have set the image in CSS but i dont know how i would change the image depending on the value.

Here is my code:

Page code:

<asp:DataList ID="dlTeam" runat="server" RepeatColumns="3" RepeatDirection="Horizontal">
            <ItemTemplate>
                <div class="teamPlayerStyle" playercode='<%# Eval("playerCode") %>'
                position='<%# Eval("position") %>' team='<%# Eval ("team") %>'
                 playername='<%# Eval ("playerName") %>' value='<%# Eval ("playerValue") %>'
                  id='item_<%# Container.ItemIndex + 1 %>'>
                    <li>
                        <%# Eval("playerCode") %>
                    </li>
                    <li>
                        <%# Eval("position") %>
                    </li>
                    <li>
                        <%# Eval ("team") %>
                    </li>
                    <li>
                        <%# Eval ("playerName") %>
                    </li>
                    <li>
                        <%# Eval ("playerValue") %>
                    </li>
                 </div>
            </ItemTemplate>
        </asp:DataList>

The code behind is:

protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }
    private void BindData()
    {
        object players = GetPlayers();

        dlTeam.DataSource = players;
        dlTeam.DataBind();
    }
    private object GetPlayers()
    {
        ArrayList playerList = new ArrayList();
        PlayersDataSetTableAdapters.TeamsTableAdapter teamAdapter = new
             PlayersDataSetTableAdapters.TeamsTableAdapter();
        DataTable dt = new DataTable();
        dt = teamAdapter.GetDataByTeamName("Team1");

        foreach (DataRow dr in dt.Rows)
        {
            Player player = new Player();
            player.playerCode = Convert.ToInt32(dr["Code"]);
            player.playerName = dr["Name"].ToString();
            player.position = dr["Position"].ToString();
            player.team = dr["Team"].ToString();
            player.playerValue = Convert.ToDecimal(dr["Value"]);
            playerList.Add(player);
        }
        return playerList;
    }

I have an image folder that contains an image for every team so for example, if the first datalist team node = "Liverpool" then the datalist item background should be set to Liverpool.gif and then the same for each team.

Any help is much appreciated.

Check this: http://msdn.microsoft.com/en-us/library/6y92e1ze(VS.80).aspx

You will have to use ItemDataBound Event like shown below:

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
           e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataRowView dv = (DataRowView)e.Item.DataItem;
            if (dv.Row["Team"].ToString() == "LiverPool")
            {
                //e.Item.BackColor = Color.YellowGreen;
                e.Item.CssClass ="liverpool";
            }
        }
    }

Thanks for your response.

That is some good stuff and it will solve half of the problem although there is still an issue with changing the image file path.

The code you have given will set a css class for the datalist item but it is the background image path in the css that i need to change,

eg:
My css for the datalist item contains the following code

.dataListItemStyle
{
	width:80px;
	height:100px;
	margin: 2px 2px 2px 2px;
                background-image:url(./images/Liverpool.gif);                
                background-repeat:no-repeat;
                background-position:top right;
                font-size:small;
                font-weight:normal;
	padding-top:34px;
	border:solid 2px black;
	z-index:99999;
}

I need to be able to change the background-image:url so that the .gif file set depending on the team name.

Thanks for your help.

can you try the code below instead of css.
here the" url(...)" string you should determine dynamically per your teamname.

e.Item.Style["background-image"] = "url(/images/Liverpool.gif)";

I have tried two different lines of code but neither have worked,

e.Item.Attributes.CssStyle.Add("background-image", "url(./images/Arsenal.gif)");

                e.Item.Style["background-image"] = "url(./images/Arsenal.gif)";

The code is being run as i have stepped through but the image is not being set.

ok check this:
1: when page is displayed in the browser can you view source and see if style is added to the item
2: its the path and so can you try removing '.' from your path

e.Item.Style["background-image"] = "url(/images/Liverpool.gif)";

the above works for me and displays an image

sorry what works for me is:

e.Item.Style["background-image"] = "url(images/test1.jpg)";

NOTE: I don't have ./ in front of images

Sorry to say this but still no joy. I have looked at the rendered source and there is no mention of the background-image.

Is it because there is a cssclass applied to the datalist items?

oh I see....looks Repeat Layout could be the issue. I have a cssClass for ItemStlye.
check my test DL code:

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" 
            Width="114px" onitemdatabound="DataList1_ItemDataBound" 
            RepeatLayout="Flow">
            <ItemStyle CssClass="dataListItemStyle" />
            <ItemTemplate>           
                UserName:
                <asp:Label ID="shoutLabel" runat="server" Text='<%# Eval("Username") %>' />
                <br />
                <br />               
            </ItemTemplate>
        </asp:DataList>

Hi thanks again for response.

Yes i can see the differences int he code you have given where you have directly applied the cssclass to the itemstyle tag. The issue i have now is that i am using this as a drag and drop area which is quite like a shopping basket. I am using jquery to implement the drag and drop and there is some javascript included to make it function. I have defined a div block inside my datalist item template and then declared some user defined attributes so that the javascript can use them to reference, such as the item attribute which increments a number to pass to the javascript.

HTML

<asp:DataList ID="dlTeam" runat="server" RepeatColumns="3" 
            RepeatDirection="Horizontal" onitemdatabound="dlTeam_ItemDataBound">
            
            <ItemTemplate>
                <div class="teamPlayerStyle" playercode='<%# Eval("Code") %>'
                position='<%# Eval("Position") %>' team='<%# Eval ("Team") %>'
                 playername='<%# Eval ("Name") %>' value='<%# Eval ("Value") %>'
                  id='item_<%# Container.ItemIndex + 1 %>'>
                    <li>
                        <%# Eval("Code") %>
                    </li>
                    <li>
                        <%# Eval("Position") %>
                    </li>
                    <li>
                        <%# Eval ("Team") %>
                    </li>
                    <li>
                        <%# Eval ("Name") %>
                    </li>
                    <li>
                        <%# Eval ("Value") %>
                    </li>
                 </div>
                 
            </ItemTemplate>
        </asp:DataList>

javascript

<script language="javascript" type="text/javascript">
    var total = 0;

    $(document).ready(function() {

        $(".teamPlayerStyle").draggable({ helper: "clone", opacity: "0.5" });

        $(".dropZone").droppable(

        {
            accept: ".teamPlayerStyle",
            hoverClass: "dropHover",
            drop: function(ev, ui) {

                var droppedItem = ui.draggable.clone().addClass("droppedItemStyle");

                var productCode = droppedItem[0].attributes["playerCode"].nodeValue;
                var productPrice = getFormattedPrice(droppedItem[0].attributes["value"].nodeValue);

                var removeLink = document.createElement("a");
                removeLink.innerHTML = "Remove";
                removeLink.className = "deleteLink";
                removeLink.href = "#";
                removeLink.onclick = function() {
                    $(".dropZone").children().remove("#" + droppedItem[0].id);
                    updateTotal(productPrice * (-1));
                }

                droppedItem[0].appendChild(removeLink);

                $(this).append(droppedItem);

                updateTotal(productPrice);
            }

        }

        );


    });
    // format the code and remove junky stuff! 
    function getFormattedPrice(unformattedPrice) {

        return unformattedPrice.replace(/[\n\r\t$/\s/g]/g, '');           
    }    

    // update the total!
    function updateTotal(price) {

        total += parseFloat(price);
        $("#total").html(total.toFixed(2));
        $(".shoppingCartTotal").effect("bounce");
    
    }
</script>

Can i still adjust the item template so that the javascript can access the datalist nodes??

I have now solved this and all it took in the end was a little javascript

for (var i = 1; i < 12; i++){
            var div = document.getElementById('item_' + i);
            var newImages = "url(images/" + div.attributes["team"].nodeValue + ".gif)";
            div.style.backgroundImage = newImages;
        }
    }

Thanks very much for your help on this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.