locked
Show text if price=0 on Search page RRS feed

  • Question

  • User-390097995 posted

    I have the If-Then statement on the ShowAd.aspx page where if the Price=0 the "Call for Price" is displayed.  However, I am not able to locate where to place a similar If-Then statement for the Search.aspx page where all of the listings for a particluar category are displayed by rows.

    Any suggestions?

    Thanks, Tim

    Friday, March 4, 2011 1:08 AM

Answers

  • User-610330605 posted

    Oh no the code I gave was in C# and you pasted it in your VB.NET code. You didnt mention that you need VB.NET code.

    Anyway use this VB.NET code instead

    Protected Sub AdsGrid_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    	If e.Row.RowType = DataControlRowType.DataRow Then
    		' display "Call for Price" if Price=0  
    		If Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Price")) = 0 Then
    			e.Row.Cells(3).Text = "Call for Price"
    		End If
    	End If
    End Sub
    
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 8, 2011 6:48 PM

All replies

  • User1113735518 posted

    put your condition to itemdatabound event of the grid

    Friday, March 4, 2011 5:43 AM
  • User-610330605 posted

    Assuming that you have to display it in the 6th column

     

    void ResultsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // display "Call for Price" if Price=0
            if (Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Price")) == 0)
            {
                e.Row.Cells[5].Text = "Call for Price";
            }
        }
    }
    Friday, March 4, 2011 5:58 AM
  • User814673218 posted

    Hi,

    You can even get direct value from SQL itself also with CASE statement.

    CASE WHEN Price = 0 THEN 'Call for Price' ELSE CONVERT(VARCHAR(10),Price) END AS Price

    Bind the Price column in listing.

    Hope it helps.

    Friday, March 4, 2011 6:07 AM
  • User-610330605 posted

    You have to decide where to handle this logic (code-behind / Entity class / stored procedure) based on the architecture you follow.

    Friday, March 4, 2011 6:16 AM
  • User-390097995 posted

    @JerryJoseph - Where is this code placed?

    Thanks for the help.

    Saturday, March 5, 2011 4:33 PM
  • User-610330605 posted
    That code should be in code-behind (Search.aspx.cs).. It is written based on the assumption that the ID of your GridView is ResultsGridView and the column number is 6.. Make necessary changes.. If you paste your GridView code I can give you accurate code..
    Saturday, March 5, 2011 10:35 PM
  • User-390097995 posted

    <asp:GridView ID="AdsGrid" runat="server" DataSourceID="AdSearchDataSource" AutoGenerateColumns="False"
         DataKeyNames="Id" AllowPaging="True" PageSize="15" AllowSorting="True" BorderWidth="0px"
         CssClass="item_list">
         <EmptyDataTemplate>
          No Ads were found matching your query.
         </EmptyDataTemplate>
         
         
         <Columns>
          <asp:ImageField DataImageUrlFormatString="~/PhotoDisplay.ashx?photoid={0}&amp;size=small"
           DataImageUrlField="PreviewImageId" SortExpression="PreviewImageId" AlternateText="Ad preview photo.">
           <ItemStyle CssClass="col_photo" />
           <HeaderStyle CssClass="col_photo" />
          </asp:ImageField>
          <asp:BoundField HeaderText="Start Date" DataField="DateCreated" SortExpression="DateCreated"
           DataFormatString="{0:MM/dd/yy}" HtmlEncode="False">
           <ItemStyle CssClass="col_startdate" />
           <HeaderStyle CssClass="col_startdate" />
          </asp:BoundField>
          <asp:HyperLinkField HeaderText="Title" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="~/ShowAd.aspx?id={0}"
           DataTextField="Title" SortExpression="Title">
           <ItemStyle CssClass="col_title" />
           <HeaderStyle CssClass="col_title" />
          </asp:HyperLinkField>
          <asp:BoundField HeaderText="Price" DataField="Price" SortExpression="Price" DataFormatString="{0:c2}"
           HtmlEncode="False">
           <ItemStyle CssClass="col_price" />
           <HeaderStyle CssClass="col_price" />
          </asp:BoundField>
          <asp:BoundField HeaderText="Location" DataField="Location" SortExpression="Location">
           <ItemStyle CssClass="col_location" />
           <HeaderStyle CssClass="col_location" />
          </asp:BoundField>
          <asp:BoundField HeaderText="Category" DataField="CategoryName" SortExpression="CategoryName">
           <ItemStyle CssClass="col_category" />
           <HeaderStyle CssClass="col_category" />
          </asp:BoundField>
          <asp:BoundField HeaderText="Condition" DataField="Condition" SortExpression="Condition">
           <ItemStyle CssClass="col_location" />
           <HeaderStyle CssClass="col_location" />
          </asp:BoundField>
          <%--<asp:TemplateField SortExpression="Title" HeaderText="Type">
           <ItemTemplate>
            <%# OutputFormatting.AdTypeToString(Eval("AdType")) %>
           </ItemTemplate>
           <ItemStyle CssClass="col_general" />
           <HeaderStyle CssClass="col_general" />
          </asp:TemplateField>--%>
         </Columns>
         <RowStyle CssClass="row1"></RowStyle>
         <AlternatingRowStyle CssClass="row2"></AlternatingRowStyle>
         <PagerStyle CssClass="item_list_footer" />
        </asp:GridView>

    Tuesday, March 8, 2011 12:55 PM
  • User-610330605 posted

    Add the databound event to the Grid in Search.aspx

    <asp:GridView ID="AdsGrid" runat="server" DataSourceID="AdSearchDataSource" AutoGenerateColumns="False" 
    DataKeyNames="Id" AllowPaging="True" PageSize="15" AllowSorting="True" OnRowDataBound="AdsGrid_RowDataBound"
    BorderWidth="0px" CssClass="item_list">

    Search.aspx.cs should contain the method below.

    protected void AdsGrid_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
            // display "Call for Price" if Price=0 
            if (Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Price")) == 0) 
            { 
                e.Row.Cells[3].Text = "Call for Price"; 
            } 
        } 
    }
    Tuesday, March 8, 2011 1:23 PM
  • User-390097995 posted

    @jerryJoseph - Thanks for all the help but I am now receiving an "End of statement expected" error in my code behind. 

    Tim

    Tuesday, March 8, 2011 5:28 PM
  • User-610330605 posted

    @jerryJoseph - Thanks for all the help but I am now receiving an "End of statement expected" error in my code behind. 

    Which line?

    Paste the error.

    Tuesday, March 8, 2011 5:53 PM
  • User-390097995 posted

    The error is on the new code highlighted below.  Thanks for the help.

    Imports System
    Imports System.Web.UI.WebControls

    Imports AspNet.StarterKits.Classifieds.BusinessLogicLayer
    Imports AspNet.StarterKits.Classifieds.Web

    Partial Class Search_aspx
     Inherits System.Web.UI.Page

     ' To customize the search experience so that the page
     ' will display a Category Browse view as seen on the homepage
     ' instead of search results, set this to false. Setting to false
     ' will only display Category Browse for top level category.
     ' Note: how search behaves for an empty search string is
     ' related to the behavior set here. See the GetAdsByQuery method
     ' in the App_Code/BLL/Ads.cs file.

        Private _showCategoryBrowseForTopLevel As Boolean = True
        Private _advancedSearchInEffect As Boolean

        protected void AdsGrid_RowDataBound(object sender, GridViewRowEventArgs e) 
        { 
            if (e.Row.RowType == DataControlRowType.DataRow) 
            { 
                // display "Call for Price" if Price=0 
                if (Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Price")) == 0) 
                { 
                e.Row.Cells[3].Text = "Call for Price"; 
                } 
            } 
        }

     Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

      _advancedSearchInEffect = Convert.ToBoolean(ViewState("advancedSearchInEffect"))
      If Not Page.IsPostBack AndAlso Page.PreviousPage Is Nothing Then
       ' check if the URL contains a query for ads by a given member
       Dim memberQs As String = Request.QueryString("member")
       If Not (memberQs Is Nothing) Then
        _showCategoryBrowseForTopLevel = True
        ' pass it on to the hidden AdvSearch control (its stores most search parameters)
        AdvancedSearch.SetMemberName(memberQs)
        _advancedSearchInEffect = True
        ViewState("advancedSearchInEffect") = True
       End If

       ' check if the URL contains a query for ads in a given category
       Dim categoryQs As String = Request.QueryString("c")
       Dim categoryIdQs As Integer = DefaultValues.CategoryIdMinValue
       If Not (categoryQs Is Nothing) Then
        If Int32.TryParse(categoryQs, categoryIdQs) Then
         _showCategoryBrowseForTopLevel = True
        End If
       End If
       ' if no category was specified in the QueryString, we set it the "All Categories" id (0)
       SetCurrentCategory(categoryIdQs)
       If (_advancedSearchInEffect) Then
        SetSearchMessage(2)
       Else
        SetSearchMessage(1)
       End If
      End If

      If (Page.IsPostBack) Then
       If (_advancedSearchInEffect) Then
        SetSearchMessage(2)
       Else
        SetSearchMessage(1)
       End If
       UpdateUI()
      End If
      If Not (Page.PreviousPage Is Nothing) Then
       ' we check if the request was cross-posted by AdvancedSearch.aspx (in which case we expect to find a control "AdvancedSearch")
       Dim advParameters As AdvancedSearch_ascx = CType(Util.FindControlRecursively("AdvancedSearch", Page.PreviousPage.Controls), AdvancedSearch_ascx)
       If (Not (advParameters Is Nothing) AndAlso advParameters.SearchingByAdvancedCriteria) Then
        ' we import its properties into the (hidden) AdvancedSearch control on this page
        AdvancedSearch.ImportProperties(advParameters)

        ' copy the values which the AdSearchDataSource needs on this page (SearchTerm comes from SearchTermTextBox, Category comes from the CategoryDropDown control)
        SetCurrentCategory(AdvancedSearch.CategoryId)
        SearchTermTextBox.Text = AdvancedSearch.SearchTerm

        SetSearchMessage(2)
        ViewState("advancedSearchInEffect") = True

       ElseIf (Not (advParameters Is Nothing) AndAlso Not (advParameters.SearchTerm.Equals(String.Empty))) Then

        ' carry over just search term as regular search in category
        SearchTermTextBox.Text = advParameters.SearchTerm
        SetCurrentCategory(AdvancedSearch.CategoryId)
        SetSearchMessage(1)
        ViewState("advancedSearchInEffect") = False

       Else
        ' a number of pages contain a generic search text box, which posts back to this page.
        ' if found, import the search term text
        Dim CommonSearchTextBox As TextBox = CType(Util.FindControlRecursively("CommonSearchTextBox", Page.PreviousPage.Controls), TextBox)

        If Not (CommonSearchTextBox Is Nothing) Then
         ' query came from Master Page Search Box
         SearchTermTextBox.Text = Server.HtmlEncode(CommonSearchTextBox.Text)
        End If

        ' if a category was also specified, import it as well
        Dim CommonCategoryDropDown As CategoryDropDown_ascx = CType(Util.FindControlRecursively("CommonCategoryDropDown", Page.PreviousPage.Controls), CategoryDropDown_ascx)
        If Not (CommonCategoryDropDown Is Nothing) Then
         SetCurrentCategory(CommonCategoryDropDown.CurrentCategoryId)
        End If
        ' if a "What's new within the last x days" was specified, import it
        Dim CommonWhatsNewRangeList As DropDownList = CType(Util.FindControlRecursively("CommonWhatsNewRangeList", Page.PreviousPage.Controls), DropDownList)
        Dim CommonWhatsNewButton As Button = CType(Util.FindControlRecursively("CommonWhatsNewButton", Page.PreviousPage.Controls), Button)
        If (Not (CommonWhatsNewRangeList Is Nothing) AndAlso Not (SearchTermTextBox.Text.Equals(String.Empty))) Then
         Dim numDays As Integer = Convert.ToInt32(CommonWhatsNewRangeList.SelectedValue)
         AdvancedSearch.DayRange = numDays
         SetSearchMessage(2)
        Else
         SetSearchMessage(1)
        End If
       End If
      End If
     End Sub

     Protected Sub SetCurrentCategory(ByVal categoryId As Integer)
      CategoryDropDown.CurrentCategoryId = categoryId
      CategoryPath.CurrentCategoryId = categoryId
      AdvancedSearch.CategoryId = categoryId
      SubcategoriesList.DataBind()
      UpdateUI()
     End Sub

     Protected Sub SetSearchMessage(ByVal flag As Integer)

      Select Case flag
       Case 1
        NormalSearch.Visible = True
        SearchingByAdvancedPanel.Visible = False
        If (SearchTermTextBox.Text.Length > 0) Then

         NormalSearchLabel.Text = "Searching with "
         NormalSearchCriteria.Text = "search term = """ & Server.HtmlEncode(SearchTermTextBox.Text) & """"
         NormalSearchCriteria.Visible = True
         ClearSearch.Visible = True

        Else

         NormalSearchLabel.Text = "No search terms <br/> specified."
         NormalSearchCriteria.Visible = False
         ClearSearch.Visible = False

        End If

       Case 2
        NormalSearch.Visible = False
        SearchingByAdvancedPanel.Visible = True
        Dim sb As New System.Text.StringBuilder()
        If (AdvancedSearch.MaximumPrice <> -1) Then
         sb.Append("max price = """ & AdvancedSearch.MaximumPrice.ToString() & """ <br/>")
        End If
        If (AdvancedSearch.Location.Length > 0) Then
         sb.Append("location = """ & Server.HtmlEncode(AdvancedSearch.Location) & """ <br/>")
        End If
        If (AdvancedSearch.AdType <> 0) Then
         sb.Append("ad type = """ & CType(AdvancedSearch.AdType, AdType) & """ <br/>")
        End If
        If (AdvancedSearch.MustHavePhotos) Then
         sb.Append("photo = """ & AdvancedSearch.MustHavePhotos & """ <br/>")
        End If
        If (AdvancedSearch.MemberName <> String.Empty) Then
         sb.Append("Ads posted by <br/>""" & AdvancedSearch.MemberName & """")
        End If
        If (AdvancedSearch.DayRange <> -1) Then
         Dim numDays As Integer = Convert.ToInt32(AdvancedSearch.DayRange)
         If (numDays = 1) Then
          sb.Append("Ads for the last day")
         Else
          sb.Append(String.Format("Ads for the last {0} days", numDays))
         End If
        End If
        AdvancedSearchCriteria.Text = sb.ToString()

       Case Else
        NormalSearch.Visible = False
        SearchingByAdvancedPanel.Visible = False
      End Select
     End Sub
     Protected Sub UpdateUI()
      Dim showSearchResults As Boolean = False
      If _showCategoryBrowseForTopLevel Then
       showSearchResults = True
      ElseIf (CategoryDropDown.CurrentCategoryId <> DefaultValues.CategoryIdMinValue) Then
       showSearchResults = True
      ElseIf Not (String.IsNullOrEmpty(SearchTermTextBox.Text)) Then
       showSearchResults = True
      End If

      If showSearchResults Then
       ' if search criteria were specified, show GridView with search results
       BrowsePanel.Visible = False
       ResultsPanel.Visible = True
       ResultsPanel.DataBind()
      Else
       ' if no search critieria were specified, show the regular browse category view (as on Default.aspx)
       BrowsePanel.Visible = True
       ResultsPanel.Visible = False
       BrowsePanel.DataBind()
      End If
     End Sub


     Protected Sub CategoryPath_CategorySelectionChanged(ByVal sender As Object, ByVal e As CategorySelectionChangedEventArgs)
      ResetSearchCriteria(True, False, False)
      SetCurrentCategory(e.CategoryId)
     End Sub

     Protected Sub CategoryDropDown_CategorySelectionChanged(ByVal sender As Object, ByVal e As CategorySelectionChangedEventArgs)
      SetCurrentCategory(e.CategoryId)
     End Sub


     Protected Sub CategoryBrowse_CategorySelectionChanged(ByVal sender As Object, ByVal e As CategorySelectionChangedEventArgs)
      Dim categoryId As Integer = Convert.ToInt32(e.CategoryId)
      SetCurrentCategory(categoryId)
     End Sub


     Protected Sub SubcategoriesList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
      If SubcategoriesList.SelectedIndex <> -1 Then
       Dim categoryId As Integer = Convert.ToInt32(SubcategoriesList.SelectedValue)
       If categoryId = -1 Then
        ResetSearchCriteria(False, False, False)
        SetCurrentCategory(CategoryPath.CurrentParentCategoryId)
       ElseIf (categoryId > -1) Then
        ResetSearchCriteria(False, False, False)
        SetCurrentCategory(categoryId)
       End If
      End If
     End Sub

     Protected Sub SubcategoriesList_DataBound(ByVal sender As Object, ByVal e As EventArgs)
      If SubcategoriesList.Items.Count = 0 Then
       SubcategoriesList.Items.Add(New ListItem("--No sub-categories. Go up one level.", "-1"))
      ElseIf (CategoryPath.CurrentCategoryId <> CategoryPath.CurrentParentCategoryId) Then
       SubcategoriesList.Items.Insert(0, New ListItem("--Go up one level.", "-1"))
      End If
     End Sub


     Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As EventArgs)
      ' when the Search button is clicked,
      ' all search parameters except the current category (from dropdown)
      ' and the search term are cleared
      ResetSearchCriteria(False, False, False)
      If (_advancedSearchInEffect) Then
       SetSearchMessage(2)
      Else
       SetSearchMessage(1)
      End If
      UpdateUI()
     End Sub

     Protected Sub RemoveAdvancedSearch_Click(ByVal sender As Object, ByVal e As EventArgs)

      ResetSearchCriteria(False, False, True)
      SetSearchMessage(1)

     End Sub

     Protected Sub ClearSearch_Click(ByVal sender As Object, ByVal e As EventArgs)

      ResetSearchCriteria(True, False, True)
      SetSearchMessage(1)

     End Sub

     Protected Sub ResetSearchCriteria(ByVal resetSearchTerm As Boolean, ByVal resetCategory As Boolean, ByVal resetAdvancedSearch As Boolean)
      If resetSearchTerm Then
       SearchTermTextBox.Text = String.Empty
      End If
      If resetCategory Then
       SetCurrentCategory(DefaultValues.CategoryIdMinValue)
      End If
      If (resetAdvancedSearch) Then
       ViewState("advancedSearchInEffect") = False
       AdvancedSearch.ResetProperties(resetSearchTerm, resetCategory)
      End If
     End Sub

    End Class

    Tuesday, March 8, 2011 5:55 PM
  • User-610330605 posted

    Oh no the code I gave was in C# and you pasted it in your VB.NET code. You didnt mention that you need VB.NET code.

    Anyway use this VB.NET code instead

    Protected Sub AdsGrid_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    	If e.Row.RowType = DataControlRowType.DataRow Then
    		' display "Call for Price" if Price=0  
    		If Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Price")) = 0 Then
    			e.Row.Cells(3).Text = "Call for Price"
    		End If
    	End If
    End Sub
    
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 8, 2011 6:48 PM
  • User-390097995 posted

    Duh.  I didnt even notice in my furor to get it fixed.  But thank you very much for the help.  IT worked like a charm.  You rock.

    Thank you,
    Tim

    Wednesday, March 9, 2011 9:59 AM
  • User1988740161 posted

    Hi, I'm not sure if I'm supposed to start a new thread.  I'm trying to do the same thing and it isn't working.  I don't get any error, but the price still shows as $0.00.  I'm using the exact same vb code for displaying "Call for Price" in my search.aspx.vb file.  Is there something more I should be checking?  Thanks.

    Wednesday, March 9, 2011 9:00 PM
  • User-382622159 posted

    Did you change both sets of code i.e. the code behind in Search.aspx and the VB in Search.aspx.vb? If anyone is interested I made alittle tweek to the code in ShowAd.aspx.vb to prevent the price from being displayed when it is zero:

    Add an If/Then to the Protected Sub AdDetails, as follows:-

     

    If ad.Price = 0

    Then

     

    AdPriceLabel.Text = "Call for Price "

    End If 

    Saturday, April 9, 2011 1:35 PM