Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 423
  • Last Modified:

How to use an If Statment to check values from a Datalist.

I want to check each row in the datalist and if the the field t9 = true then add the imageplaceholder in my ItemTemplate (and populate it with url value from the database)

Here is the code below
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1"
                    RepeatColumns="2" RepeatDirection="Horizontal" CellPadding="2" BackColor="#D8D8D8" Width="463" OnSelectedIndexChanged="DataList1_SelectedIndexChanged">
                    <ItemTemplate>
                        &nbsp;<a href='maps.aspx?eventID=<%# Eval("id") %>'><strong><%# Eval("t2") %></strong></a>&nbsp;
                    </ItemTemplate>
                    <SelectedItemStyle BackColor="Red" Font-Bold="False" Font-Italic="False" Font-Overline="False"
                        Font-Strikeout="False" Font-Underline="False" />
                         </asp:DataList>
0
quest_capital
Asked:
quest_capital
  • 14
  • 11
1 Solution
 
jeebukarthikeyanCommented:
hi,

change the item template like this

<ItemTemplate>
    <asp:PlaceHolder Runat="server" ID="plc"></asp:PlaceHolder>
</ItemTemplate>

add a place holder control in the item template

add an item databound event for the datalist


      
               private void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
            {
                  DataRowView drv=(DataRowView) e.Item.DataItem;

                  if(e.Item.ItemIndex>=0)
                  {
                        PlaceHolder plc;

                        if(drv["t2"].ToString()=="true" )
                        {
                              plc=(PlaceHolder) e.Item.FindControl("plc");
                              LiteralControl lt=new LiteralControl();
                              lt.Text="jj";
                              plc.Controls.Add(lt);

                        }
                  }
            }

i doubt y u r going for place holder for adding an url....u can use a label control for that

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan
thx for the post

What about my other controls that are is the <ItemTemplate>
 &nbsp;<a href='maps.aspx?eventID=<%# Eval("id") %>'><strong><%# Eval("t2") %></strong></a>&nbsp;
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan
Do this

<ItemTemplate>
                        &nbsp;<a href='maps.aspx?eventID=<%# Eval("id") %>'><strong><%# Eval("t2") %></strong></a>&nbsp; <asp:PlaceHolder Runat="server" ID="plc"></asp:PlaceHolder>
                    </ItemTemplate>
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
jeebukarthikeyanCommented:
hi,
other controls in the item template will not affect

we are only aiming at the place holder control

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

How do I add a value from the field like
<%# Eval("t9") %> see below

Iknow that this is wrong but you should get what I mean
plc=(PlaceHolder) e.Item.FindControl("plc");
                         LiteralControl lt=new LiteralControl();
                         lt.Text="<a href=>"+<%# Eval("t9") %>+"</a>"; //////// look here
                         plc.Controls.Add(lt);
0
 
jeebukarthikeyanCommented:
hi,

     private void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
          {
               DataRowView drv=(DataRowView) e.Item.DataItem;

               if(e.Item.ItemIndex>=0)
               {
                    PlaceHolder plc;

                    if(drv["t2"].ToString()=="true" )
                    {
                         plc=(PlaceHolder) e.Item.FindControl("plc");
                         LiteralControl lt=new LiteralControl();
                         lt.Text="<a href=\"" + drv["t9"].ToString() + "\">" +drv["t9"].ToString() +" /a>";                          
                   plc.Controls.Add(lt);

                    }
               }
          }


b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

I could not get this to work I did a bit of modification be i'm not sure if that made it better or worse.


Code:
------------------------------------------------------------------------------------------------
void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {

        String eventID = Request.QueryString["EventID"];
        if (eventID == null)
        {
            eventID = "321";
        }

        DataRowView drv = (DataRowView)e.Item.DataItem;
        if (e.Item.ItemIndex >= 0)
        {
            if (drv["ID"].ToString() == eventID)
            {
                PlaceHolder plc = (PlaceHolder)e.Item.FindControl("PlaceHolder2");
                LiteralControl lt = new LiteralControl();
                lt.Text = "<<";
                plc.Controls.Add(lt);
            }
        }
    }

------------------------------------------------------------------------------------------------------------
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1"
                    RepeatColumns="2" RepeatDirection="Horizontal" CellPadding="2" BackColor="#D8D8D8" Width="463">
                    <ItemTemplate>
                        &nbsp;<a href='maps.aspx?eventID=<%# Eval("id") %>'><strong><%# Eval("t2") %></strong></a>&nbsp;
                        <asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
                    </ItemTemplate>
                    <SelectedItemStyle BackColor="Red" Font-Bold="False" Font-Italic="False" Font-Overline="False"
                        Font-Strikeout="False" Font-Underline="False" />
                    <HeaderTemplate>
                        <strong>&nbsp;Events</strong><br /><br />
                    </HeaderTemplate>
                    <FooterTemplate>
                        <br />
                        &nbsp;Click on an event to map
                    </FooterTemplate>
                </asp:DataList>
0
 
jeebukarthikeyanCommented:
hi,

is there any error poping up

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan
no error
0
 
jeebukarthikeyanCommented:
hi,

then r u getting the results
where its failing

just put a break point in the
   if (e.Item.ItemIndex >= 0)

and check the flow

b u d d h a
0
 
quest_capitalAuthor Commented:

It not even going to it (is it placement) here is the full code behide.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class maps : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String eventID = Request.QueryString["EventID"];
        if (eventID == null)
       {
            eventID = "286";
        }
       
        string connectionString = ConfigurationSettings.AppSettings["qeConnectionString"];
        SqlConnection dbConnection = new SqlConnection(connectionString);
        dbConnection.Open();
        //SqlCommand cmd = new SqlCommand("SELECT * FROM [tbl1]", dbConnection);

        SqlCommand cmd = new SqlCommand("Events_Select", dbConnection);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@EventID", eventID);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet("tbl1");
        da.Fill(ds);

        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            HiddenField txt = new HiddenField();
            txt.ID = "tb_Location" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t8"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_GroupName" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t1"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_EventTitle" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t2"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_EventDate" + i.ToString();//id creation
            txt.Value = Convert.ToDateTime(ds.Tables[0].Rows[i]["t5"]).ToString("ddd. MM.dd.yyyy");
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_EventTime" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t6"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_EventPlace" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t7"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_EventContent" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t3"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_EventLink1" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["t4"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_City" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["city"].ToString();
            PlaceHolder1.Controls.Add(txt);

            txt = new HiddenField();
            txt.ID = "tb_State" + i.ToString();//id creation
            txt.Value = ds.Tables[0].Rows[i]["state"].ToString();
            PlaceHolder1.Controls.Add(txt);
        }

   }
    void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {

        String eventID = Request.QueryString["EventID"];
        if (eventID == null)
        {
            eventID = "321";
        }

        DataRowView drv = (DataRowView)e.Item.DataItem;
        if (e.Item.ItemIndex >= 0)
        {
            if (drv["ID"].ToString() == eventID)
            {
                PlaceHolder plc = (PlaceHolder)e.Item.FindControl("PlaceHolder2");
                LiteralControl lt = new LiteralControl();
                lt.Text = "<<";
                plc.Controls.Add(lt);
            }
        }
    }
}
0
 
jeebukarthikeyanCommented:
hi,

It not even going to it ????
DataList1_ItemDataBound

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

It does not break to it
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

seems like it is not reading the code at all
0
 
jeebukarthikeyanCommented:
hi,

in this code

       string connectionString = ConfigurationSettings.AppSettings["qeConnectionString"];
        SqlConnection dbConnection = new SqlConnection(connectionString);
        dbConnection.Open();
        //SqlCommand cmd = new SqlCommand("SELECT * FROM [tbl1]", dbConnection);

        SqlCommand cmd = new SqlCommand("Events_Select", dbConnection);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@EventID", eventID);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet("tbl1");
        da.Fill(ds);

      WHERE IS THE CODE CONNECTING THE DATASET TO THE DATALIST
      something like
      DataList1.datasource=ds;
      DataList1.databind();

 b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan
that code is doing something totaly diffrent
The code for the data grid is at the bottom
Here is the  asp code

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="maps.aspx.cs" Inherits="maps" Title="Maps" Theme="QE" %>

<%@ Register Src="links.ascx" TagName="links" TagPrefix="uc2" %>
<%@ Register Src="Event1.ascx" TagName="Event1" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderContent" runat="Server">
   
    <!--start Content-->
    <div id="Content">
        <!--start Left-->
        <div id="Left">
            <div class="TextBox_ln">
                <img src="images/t_events.gif"><br>
                <br>
                <uc1:Event1 ID="Event1_1" runat="server" />
                <br>
                <img src="images/5_bun1.gif"><br>
                <br>
                <br>
                <img src="images/t_links.gif"><br>
                <br>
                <uc2:links ID="Links1" runat="server" />
            </div>
        </div>
        <!--end Left-->
        <!--Start Main-->
        <div id="main">
            <div class="TextBox">
                <img src="images/t_maps.gif"><br />
               
                <br />
                <asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="true">
                </asp:PlaceHolder>
                <script type="text/javascript" src="http://maps.yahooapis.com/v3.03/fl/javascript/apiloader.js?appid=quest2000">
                </script>

                <div id="mapContainer" style="height: 400px; width: 463px; border: thin solid #D8D8D8;">
                </div>

                <script type="text/javascript">
         
                    // Create and display Map object at the address and with zoom level 3
                    // Include your application ID.
                    var sceen = document.forms[0]['ctl00_ContentPlaceHolderContent_tb_Location0'].value;
                    //alert(sceen);
                    var map = new Map('mapContainer', 'quest2000',
                      sceen + ',Houston, TX', 7, MapViews.MAP);
                      //map.addWidget(new SatelliteControlWidget());

                    // Make the map draggable
                    map.addTool( new PanTool(), true );
                    // Create a POI marker object
                    //marker1 = new CustomPOIMarker( 'Friday Social Essence Edition', ' Fri. 06.30.2006',
                     // '<br />QE, ISISPAGES.COM & 4tion Entertainment <br />Friday Social Essence Edition <br />Fri. 06.30.2006  5:30pm - until <br />Tribeca Lounge @ 3707 Fountainview <br /><a href="#" target="_blank">Click here for more...</a>', '0xFF0000', '0xFFFFFF');
                    // Add the POI marker to the map and display it
                    //map.addMarkerByAddress( marker1, tb_Location);
                   
                       var elem = document.forms[0].elements;
                       for( i=0;i<elem.length;i++)
                       {
                                    var dd=elem[i].id
                                    var tb=dd.substring(32);
                                    var tbz=dd.substring(0,32);
                             
                              if(elem[i].type=='hidden' && tbz=='ctl00_ContentPlaceHolderContent_')
                              {
                                   
                                    var tb_Location = tb.substring(0,11);
                                    if(tb_Location == 'tb_Location')
                                    {
                                         var Location=elem[i].value;
                                    }
                                    var tb_EventTitle = tb.substring(0,13);
                                    if(tb_EventTitle == 'tb_EventTitle')
                                    {
                                         var EventTitle =elem[i].value;
                                    }
                                    var tb_EventDate = tb.substring(0,12);
                                    if(tb_EventDate == 'tb_EventDate')
                                    {
                                         var EventDate =elem[i].value;
                                    }
                                    var tb_GroupName = tb.substring(0,12);
                                    if(tb_GroupName == 'tb_GroupName')
                                    {
                                         var GroupName =elem[i].value;
                                    }
                                    var tb_EventTime = tb.substring(0,12);
                                    if(tb_EventTime == 'tb_EventTime')
                                    {
                                         var EventTime =elem[i].value;
                                    }
                                    var tb_EventPlace = tb.substring(0,13);
                                    if(tb_EventPlace == 'tb_EventPlace')
                                    {
                                         var EventPlace =elem[i].value;
                                    }
                                    var tb_EventContent = tb.substring(0,15);
                                    if(tb_EventContent == 'tb_EventContent')
                                    {
                                         var EventContent =elem[i].value;
                                    }
                                    var tb_EventLink1 = tb.substring(0,13);
                                    if(tb_EventLink1 == 'tb_EventLink1')
                                    {
                                         var EventLink1 =elem[i].value;
                                    }
                                    var tb_City = tb.substring(0,7);
                                    if(tb_City == 'tb_City')
                                    {
                                         var City =elem[i].value;
                                    }
                                    var tb_State = tb.substring(0,8);
                                    if(tb_State == 'tb_State')
                                    {
                                         var State =elem[i].value;
                                    }
                                        //map.addMarkerByAddress(new CustomPOIMarker(EventTitle,' ' + EventDate,'<br />'+GroupName+'<br />'+EventTitle+'<br />'+EventDate+'  '+EventTime+' <br />'+EventPlace+' @ '+Location+' <br />'+EventContent+'<br /><a href="'+EventLink1+'" target="_blank">Click here for more...</a>', '0xFF0000', '0xFFFFFF'), Location + ', Houston, TX');
                                        map.addMarkerByAddress(new CustomPOIMarker(EventTitle,' Click here for details...','<br />'+GroupName+'<br />'+EventTitle+'<br />'+EventDate+'  '+EventTime+' <br />'+EventPlace+' @ '+Location+' <br />'+EventContent+'<br /><a href="'+EventLink1+'" target="_blank">Click here for more...</a>', '0x666666', '0xFFFFFF'), Location + ', '+City+', '+State+'');
                               }
                        }

                   
                    // Make the map draggable
                    map.addTool( new PanTool(), true );
                    // Create a Navigator Widget object
                    navWidget = new NavigatorWidget();  
                    // Add the Navigator Widget to the map and display it
                    map.addWidget(navWidget);

                   
                    ///////////////// Search Overlay /////////////////////////////////
                   
                    // Create global overlay variable
                     var overlay = null;
                    // Wait for the map to initialize and then call onInitialize
                    map.addEventListener(Map.EVENT_INITIALIZE, onInitialize);
                    // Search for nearby Mexican food restaurants
                    function onOverlayInit( oEvent ) {
                      overlay.search('', map.getCenter(), 1, 10);
                    }
                    function onInitialize( oEvent ) {
                      // Make  the map draggable
                      map.addTool(
                      new PanTool(), true );
                      // Create an overlay object
                      overlay = new LocalSearchOverlay();
                      // Wait for the overlay object to initialize,
                      // then call onOverlayInit
                      overlay.addEventListener(
                      Overlay.EVENT_INITIALIZE,onOverlayInit, this );
                      // Add the overlay to the map and display it
                      map.addOverlay(overlay);
                      map.addOverlay(TrafficOverlay);
                    }


                </script>

                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:qeConnectionString %>"
                    SelectCommand="Events_Select" SelectCommandType="StoredProcedure">
                </asp:SqlDataSource>
                <asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1"
                    RepeatColumns="2" RepeatDirection="Horizontal" CellPadding="2" BackColor="#D8D8D8" Width="463">
                    <ItemTemplate>
                        &nbsp;<a href='maps.aspx?eventID=<%# Eval("id") %>'><strong><%# Eval("t2") %></strong></a>&nbsp;
                        <asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
                    </ItemTemplate>
                    <SelectedItemStyle BackColor="Red" Font-Bold="False" Font-Italic="False" Font-Overline="False"
                        Font-Strikeout="False" Font-Underline="False" />
                    <HeaderTemplate>
                        <strong>&nbsp;Events</strong><br /><br />
                    </HeaderTemplate>
                    <FooterTemplate>
                        <br />
                        &nbsp;Click on an event to map
                    </FooterTemplate>
                </asp:DataList><br />
            </div>
        </div>
        <!--end Main-->
    </div>
    <!--end Content-->
</asp:Content>
0
 
jeebukarthikeyanCommented:
hi,

hope everything is going correct

in the initializecomponent()
check whether there is any entry like
this.DataList1.ItemDataBound += new System.Web.UI.WebControls.DataListItemEventHandler(this.DataList1_ItemDataBound);

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

You lost me
initializecomponent() ????
I sent you the complete page.
0
 
jeebukarthikeyanCommented:
hi,

initializecomponent()  is in the server side

this is the function that will bind all the events of controls used in the form

check that

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

I needed this
OnItemDataBound="DataList1_ItemDataBound"

now i get this

Compiler Error Message: CS0122: 'maps.DataList1_ItemDataBound(object, System.Web.UI.WebControls.DataListItemEventArgs)' is inaccessible due to its protection level
0
 
jeebukarthikeyanCommented:
hi,

if u want this OnItemDataBound="DataList1_ItemDataBound"
initializecomponent()
should contain
this.DataList1.ItemDataBound += new System.Web.UI.WebControls.DataListItemEventHandler(this.DataList1_ItemDataBound);


check iyt or
put ur server code i will check the error

b u d d h a
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

Now it is going though the code and I get the error


Object reference not set to an instance of an object <<<< see the line below

protected void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
    {

        String eventID = Request.QueryString["EventID"];
        if (eventID == null)
        {
            eventID = "286";
        }

        DataRowView drv = (DataRowView)e.Item.DataItem;

        if (e.Item.ItemIndex >= 0)
        {

            if (drv["ID"].ToString() == eventID)
            {
                PlaceHolder plc = (PlaceHolder)e.Item.FindControl("plc") as PlaceHolder;
                LiteralControl lt = new LiteralControl();
                lt.Text = "<<";
                plc.Controls.Add(lt); <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  error here

            }
        }
    }
0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

Got it !!!!!
 PlaceHolder plc = (PlaceHolder)e.Item.FindControl("plc") as PlaceHolder;
to
 PlaceHolder plc = (PlaceHolder)e.Item.FindControl("PlaceHolder2") as PlaceHolder;
0
 
jeebukarthikeyanCommented:
hi,

u wrote to me like this

jeebukarthikeyan

I could not get this to work I did a bit of modification be i'm not sure if that made it better or worse.


Code:
------------------------------------------------------------------------------------------------
void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {

        String eventID = Request.QueryString["EventID"];
        if (eventID == null)
        {
            eventID = "321";
        }

        DataRowView drv = (DataRowView)e.Item.DataItem;
        if (e.Item.ItemIndex >= 0)
        {
            if (drv["ID"].ToString() == eventID)
            {
                PlaceHolder plc = (PlaceHolder)e.Item.FindControl("PlaceHolder2");
                LiteralControl lt = new LiteralControl();
                lt.Text = "<<";
                plc.Controls.Add(lt);
            }
        }
    }

b u  d d h a

0
 
quest_capitalAuthor Commented:
jeebukarthikeyan

I have a simular question with the Gridview below.

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_22044193.html
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 14
  • 11
Tackle projects and never again get stuck behind a technical roadblock.
Join Now