Listview, Datapager and retrieving value of Label

Hi,

I am trying to use the photo_id of a picture whilst a user uses a datapager to select different images. I am also getting the photo_id of the pictures through a label within the listview. However now i need that value so i pull out comments from another table according to this photo_id…
I currently have th following code:-


<asp:ListView ID="lvPhotoViewer" runat="server" GroupItemCount="1" 
            onselectedindexchanged="lvPhotoViewer_SelectedIndexChanged">
         <LayoutTemplate>                
             <table ID="groupPlaceholderContainer" runat="server" border="1">                               
                  <tr ID="groupPlaceholder" runat="server">
                  </tr>
             </table>                       
         </LayoutTemplate>
               
         <ItemTemplate>
             <td id="Td4" align="center" style="background-color: #eeeeee;">
                    
                    <asp:Image runat="server" ID="imPhoto" Height="450px" Width="450px" ImageUrl='<%# string.Format("~/photos/{0}", Eval("photo")) %>' />
                    <br />
                    <asp:Label ID="DefaultPhotIDLabel" runat="server" Text='<%# Eval("photo_name") %>' />                    
             [B][U]       <asp:Label ID="Label5" runat="server" Text='<%# Eval("photo_id") %>'/>[/U][/B]
             </td>
        </ItemTemplate>
   
         <GroupTemplate>
              <tr ID="itemPlaceholderContainer" runat="server">
                   <td ID="itemPlaceholder" runat="server">
                   </td>
              </tr>
        </GroupTemplate>
        </asp:ListView>

        <asp:DataPager ID="DataPager1" runat="server" 
        PagedControlID="lvPhotoViewer" PageSize="1" 
        onprerender="DataPager1_PreRender">
        <Fields>
            <asp:NextPreviousPagerField ButtonType="Link"
            PreviousPageText="<< Previous" NextPageText="Next >>"/>
         </Fields>
        </asp:DataPager>

    <asp:Label ID="Label6" runat="server" Text=""></asp:Label>

So as you can see the line that i have underlined shows where i read the photo_id from. Now i want to try and retrieve this value somehow so i thought of reading it through a label on page load.

I wrote the following code where i wanted the photo_id to appear in label 5, then i would get this value and use it later…

Heres the code:-


        if (!Page.IsPostBack)
        {
            Label SourceTextBox = (Label)Page.FindControl("Label5");

            if (SourceTextBox != null)
            {
                Label6.Text = SourceTextBox.ToString();
            }
        }

This is being done on page load. But the Label6 does not read any value so it means it is not being read from the list view.

Any ideas what im doing wrong?

Regards
Billy

Does anybody know how this is done?

Best would be to get the value out on button click instead of in a label. When you bind on page load. is it in a if (!Page.IsPostBack).

Coz it seems that your lable is losing its value on the post back. Remember. Internet is stateless, so 2 requests do not have the same data unless its catered for. Either by viewstate or another mechanism.

Well, that label is in a ListView, so trying to find control like that is not going to work.

You will need to loop through the items of the ListView.

Not sure now exactly what a ListView Item is called again, but it would be something like this:


foreach (ListViewItem i in lvPhotoViewer.Items)
{
Label SourceTextBox = (Label)i.FindControl("Label5");



            if (SourceTextBox != null)

            {

                Label6.Text = SourceTextBox.Text;

            }

}

I hope this is what you are looking for. Just know, that if you have a list, this code will only get the last item into the label unless you += to the text of that lable, then it will add all of them there.

Hey thanks,

I used this method and it works fine. Now i am trying to use this value to select from a database…

I am trying to do a SELECT where i bind a repeater using the value of a label. I have tested the label to see if the value is actually outputted and it is, but the SELECT does not work…

The Label that i am retrieving the value of is actually within a Listview so i append it to another label outside of the listview so i can get access to it easily.

This is my repeater:


    <!-- start child repeater -->

    <asp:repeater id="childRepeater" runat="server" 

        onitemdatabound="childRepeater_ItemDataBound">

         <itemtemplate>

         <asp:Label ID="lblCommentID" runat="server" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "CID") %>'></asp:Label>

             <div style="height:auto;margin-bottom:12px;">

   <a href="<%# "user-wall.aspx?ID=" + Eval("UID") %>"><asp:Image ID="Image5" runat="server" ImageUrl='<%# string.Format("~/avatars/{0}", Eval("Avatar")) %>' runat="server" Width="45px" Height="45px"/></a>

      <p><a href="<%# "user-wall.aspx?ID=" + Eval("UID") %>"><%# DataBinder.Eval(Container.DataItem, "Fname") %></a> 

   - <%# DataBinder.Eval(Container.DataItem, "Comment") %>

  <br />

  <span style='float:right;font-size:11px'><asp:LinkButton ID="LinkButton1" runat="server" visible="false" OnClientClick='<%# "remove-response.aspx?ID=" + Eval("CID") %>'>remove</asp:LinkButton></span><small><%# DataBinder.Eval(Container.DataItem, "Added") %></small>

  </p>

  </div>

         </itemtemplate>

      </asp:repeater>

      <!-- end child repeater --> 

  </div>

        <div style="width: 442px; margin-top:10px; margin-left: auto; margin-right: auto; margin-bottom: auto;">

      <asp:TextBox ID="TextBox2" runat="server" CssClass="text-comment" onfocus="this.value='';" 

        onblur="if (this.value=='') this.value='Write a comment';" 

        value="Write a comment" ForeColor="#A79090" Width="339px"></asp:TextBox>

    <asp:Button ID="Button1" runat="server" Text="Submit"  

                CommandArgument='<%# Eval("CID") %>' onclick="Button1_Click"/>   

    </div> 

Then on page load i try to bind it like this:-


if (!Page.IsPostBack)

        {

            string photoID = Request.QueryString["PhotoID"];

            string albumID = Request.QueryString["AlbumID"];

            ViewState["hfAlbumID"] = albumID;

            //Get Page number by passing photo id

            int index = GetPageNumber(int.Parse(photoID), int.Parse(albumID));

            DataPager1.SetPageProperties(index, 1, true);



            string connStr1 = "Data Source=SQLB23.webcontrolcenter.com;User ID=wbsd;Password=*****;";

            SqlConnection dbConn1 = new SqlConnection(connStr1);



            dbConn1.Open();



            string sSQL = "SELECT (hussaini_album_comments.comment_id) AS CID, " +

                    "(hussaini_album_comments.comment) AS Comment, " +

                    "(hussaini_album_comments.user_id) AS UID, " +

                    "(hussaini_album_comments.date_added) AS Added, " +

                    "(hussaini_users.fname) AS Fname, " +

                    "(hussaini_users.avatar) AS Avatar " +

                    "FROM hussaini_album_comments LEFT OUTER JOIN hussaini_users ON " +

                    "hussaini_album_comments.user_id = hussaini_users.user_id WHERE hussaini_album_comments.pic_id = @pic_id";

            SqlCommand cmd = new SqlCommand(sSQL, dbConn1);



            cmd.Parameters.Add("@pic_id", SqlDbType.Char).Value = Label6.Text;



            SqlDataReader dtrCat = cmd.ExecuteReader();



            if (dtrCat.HasRows)

            {

                childRepeater.DataSource = dtrCat;

                childRepeater.DataBind();

            }

            else

            {

                Label8.Visible = true;

                Label8.Text = "<BR><i>There are no comments for this photo. Please enter something.</i><BR>";

            }

            dtrCat.Close();

            dbConn1.Close();

        } 

I retrieve the value of Label6 by using the value of Label5 which is inside a listview like so:-


    protected void lvPhotoViewer_DataBound(object sender, EventArgs e)

    {

        foreach (ListViewDataItem item in lvPhotoViewer.Items)

        {

            Label Label5 = (Label)item.FindControl("Label5");



            if (Label5.Text != null)

            {

                Label6.Text = Label5.Text;

            }

        }

    } 

So now i have the value of Label 5 inside Label 6. So in the SELECT why does Label 6 not get picked up?

To prove that it does actually get the value i manage to insert into the database on button click like so:-


 protected void Button1_Click(object sender, EventArgs e)

    {

        try

        {

            if (TextBox2.Text != "Write a comment" && TextBox2.Text != "")

            {

                string conString = "Data Source=SQLB23.webcontrolcenter.com;User ID=wbsd;Password=******";

                SqlConnection empConnection = new SqlConnection(conString);



                string insertStatement = "INSERT INTO hussaini_album_comments ([pic_id], [user_id], [comment], [date_added]) "

                    + "VALUES (@pic_id, @user_id, @comment, GetDate())";



                SqlCommand insertCommand = new SqlCommand(insertStatement, empConnection);



                insertCommand.Parameters.Add("@pic_id", SqlDbType.Char).Value = Label6.Text;

                insertCommand.Parameters.Add("@user_id", SqlDbType.Char).Value = System.Convert.ToInt32(Session["MEM_ID"].ToString());

                insertCommand.Parameters.Add("@comment", SqlDbType.Char).Value = TextBox2.Text;

                empConnection.Open();



                insertCommand.ExecuteNonQuery();



                empConnection.Close();

            }

        }

        finally

        {

            Response.Redirect("view-photo.aspx?PhotoID=" + Request.QueryString["PhotoID"].ToString() + "&AlbumID=" + Request.QueryString["AlbumID"].ToString() + "&UID=" + Request.QueryString["UID"].ToString());

        } 

    } 

See this parameter:-

insertCommand.Parameters.Add(“@pic_id”, SqlDbType.Char).Value = Label6.Text;

I am using Label 6 here and have no problems with it, so why does the SELECT in page load not work?

Hope someone can help.

Regards
Billy

Yes but the problem is that i cant get the value out on button click as i need to pull the information out when the page loads.

So i do the select and then try to retrieve the value of the label. Is there no other way i can do this?

First you need to check that the label is getting the correct text on post back. Just Response.Write it and it will be at the top of the page if it is getting it.

Also, replace this:
insertCommand.Parameters.Add(“@pic_id”, SqlDbType.Char).Value = Label6.Text;
insertCommand.Parameters.Add(“@user_id”, SqlDbType.Char).Value = System.Convert.ToInt32(Session[“MEM_ID”].ToString());
insertCommand.Parameters.Add(“@comment”, SqlDbType.Char).Value = TextBox2.Text;

with:
insertCommand.Parameters.AddWithValue(“@pic_id”, Label6.Text);
insertCommand.Parameters.Add(“@user_id”,System.Convert.ToInt32(Session[“MEM_ID”].ToString());
insertCommand.Parameters.Add(“@comment”,TextBox2.Text);

When I said get the value on the button click, i didnt mean load the data. Bind your list on page load, then on button click just loop through the ListView for your value