locked
How to pass a QueryString in ASP .NET's SelectCommand from Code Front? RRS feed

  • Question

  • User238457982 posted

    Hello,

    I have a question related to <asp:SqlDataSource's SelectCommand. How to pass a querystring like  <%# Eval("PhotoID") %>  in the selectCommand.

    The whole frontend code is attached. I put

    <%# Eval("PhotoID") %> and the photoid gets printed in the page.

    <%# Eval("PhotoID") %> is the current displayed picture's PhotoID.

    I want to pass this PhotoID or I want to pass  <%# Eval("PhotoID") %> to the select command dynamically.

    I have tried the following approaches:

    1)  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:aspnetdb %>" SelectCommand="SELECT UserName, commentDesc, uID FROM photo_comment_view Where pID = @pID">
    <SelectParameters><asp:Parameter Name="pID" DefaultValue="7" /></SelectParameters>
    </asp:SqlDataSource>

    --The above works but it gives only information about PhotoID 7, but there are other photos; How to set pID's value to <%# Eval("PhotoID") %> in ASP .NET's frontend page?

    Then I also tried,

    2)  <asp:SqlDataSource ID="SqlDataSource1" runat="server"  ConnectionString="<%$ ConnectionStrings:aspnetdb %>" SelectCommand="SELECT UserName, commentDesc, uID FROM photo_comment_view Where pID =  <%#'Eval("PhotoID') %>"></asp:SqlDataSource>

    ---Gives Parser error: Parser Error Message: The server tag is not well formed.

    What I should do so that I can pass current PhotoID to SelectCommand? Please suggest.



    The frontend code:


    <%@    Page Language="VB" MasterPageFile="~/Default.master" Title="Your Name Here | Picture Details"
        CodeFile="Details.aspx.vb" Inherits="Details_aspx" %>

    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div class="shim solid"></div>
       
      
        <div class="page" id="details">
    <%--Update Panel Here--%>
    <asp:UpdatePanel runat="server" ID="updatepanel">
      <ContentTemplate>
            <asp:formview id="FormView1" runat="server"    datasourceid="ObjectDataSource1" cssclass="view"
                borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true">
                <itemtemplate>
               
                    <div class="buttonbar buttonbar-top">
                        <a href="Albums.aspx"><asp:image ID="Image1" runat="Server"     skinid="gallery" /></a>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <asp:ImageButton ID="ImageButton9" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
                        <asp:ImageButton ID="ImageButton10"    Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
                        <asp:ImageButton ID="ImageButton11"    Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
                        <asp:ImageButton ID="ImageButton12"    Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
                    </div><br />
                    <asp:Label ID="PHOTOID" runat="server" Text=<%# Eval("PhotoID") %>></asp:Label>
                    <p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
                    <table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
                        <tr>
                            <td class="topx--"></td>
                            <td class="top-x-"></td>
                            <td class="top--x"></td>
                        </tr>
                        <tr>
                            <td class="midx--"></td>
                            <td><img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=L" class="photo_198" style="border:4px solid white" Height="100" alt='Photo Number <%# Eval("PhotoID") %>' /></a></td>
                            <td class="mid--x"></td>
                        </tr>
                        <tr>
                            <td class="botx--"></td>
                            <td class="bot-x-"></td>
                            <td class="bot--x"></td>
                        </tr>
                    </table>
                    <p><a href='Download.aspx?AlbumID=<%# Eval("AlbumID") %>&Page=<%# Container.DataItemIndex %>'>
                        <asp:image runat="Server" id="DownloadButton" AlternateText="download this photo" skinid="download" /></a></p>
                    <div class="buttonbar">
                        <a href="Albums.aspx"><asp:image ID="Image2" runat="Server"     skinid="gallery" /></a>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
                        <asp:ImageButton ID="ImageButton2" Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
                        <asp:ImageButton ID="ImageButton3" Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
                        <asp:ImageButton ID="ImageButton4" Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
                    </div>

                </itemtemplate>
            </asp:formview>

    </ContentTemplate>
    </asp:UpdatePanel>

    <%-- deleted to save space --%>

    <%--End updatepanel
    --%>       

    <%--UpdateProgress--%>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server">
                <ProgressTemplate>
                    <div id="box">
                        <img id="Img1" runat="server" alt="Loading" src="~/Images/ajax-loader.gif" /></div>
                </ProgressTemplate>
            </asp:UpdateProgress>


        </div>

        <br />
        <div id="comment" style="
      
        z-index:21;
        font-family: Verdana;height:200px;
        font-size: 10px;
        text-align:left;
        color:#333333;
        letter-spacing:.1em;
        text-align:justify;
        padding: 0;
        width: 600px;overflow:scroll;overflow-x:hidden;">
        <asp:TextBox ID="TextBox1" runat="server" Width="300" ></asp:TextBox> <br />
         <asp:Button ID="Button1" runat="server" BackColor="Transparent" Width="150" Text="Submit Your Comment"></asp:Button> <br />
         <strong style="font-size:20px; font-weight:bolder;">User's Comment</strong><br /><br />
         
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="UserName" HeaderText="UserName"
                        SortExpression="UserName" />
                    <asp:BoundField DataField="commentDesc" HeaderText="commentDesc"
                        SortExpression="commentDesc" />
                    <asp:BoundField DataField="uID" HeaderText="uID" SortExpression="uID" />
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>" SelectCommand=
                'SELECT UserName, commentDesc, uID FROM photo_comment_view Where pID = <%# Eval("PhotoID") %>'>

                </asp:SqlDataSource>

       </div>
        <br /><br /><br />
        <asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager"
            SelectMethod="GetPhotos">
            <SelectParameters>
                <asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
            </SelectParameters>
        </asp:ObjectDataSource>
       
    </asp:content>

    Friday, January 7, 2011 11:17 AM

Answers

  • User-1316079624 posted

    If you want to pass the PhotoID of the FormView1, try something like that:


    1. <asp:formview id="FormView1" runat="server" datasourceid="ObjectDataSource1" cssclass="view"
    2.     borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true"
    3.     DataKeyNames="PhotoID" >

    1. <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    2.     ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>"
    3.     SelectCommand="SELECT UserName, commentDesc, uID FROM photo_comment_view Where pID = @PhotoID" >
    4.     <SelectParameters>
    5.         <asp:ControlParameter Name="PhotoID" ControlID="FormView1" PropertyName="SelectedValue" Type="Int32"
    6.             DefaultValue="0" />
    7.     </SelectParameters>
    8. </asp:SqlDataSource>

    I hope it is useful.




     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 7, 2011 12:27 PM
  • User-1316079624 posted

    In your code, FormView1 is the data-bound control that is bound to ObjectDataSource1, so "<%# Eval("PhotoID") %>" should only be used to bind the PhotoID value to the controls that are inside the templates of the FormView1.

    Regarding my suggestion, the aim was to set FormView1.DataKeyNames = "PhotoID", so that FormView1.SelectedValue contains the PhotoID of the displayed record.

    Then used a ControlParameter to bind the value of a FormView1.SelectedValue (PhotoID) to a parameter that is used in a SQL query of the SqlDataSource1
    (I assumed that PhotoID is of type Int32; correct if I'm wrong).

    I hope I've achieved to explain my approach (sorry my english).


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 7, 2011 2:59 PM

All replies

  • User-1316079624 posted

    If you want to pass the PhotoID of the FormView1, try something like that:


    1. <asp:formview id="FormView1" runat="server" datasourceid="ObjectDataSource1" cssclass="view"
    2.     borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true"
    3.     DataKeyNames="PhotoID" >

    1. <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    2.     ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>"
    3.     SelectCommand="SELECT UserName, commentDesc, uID FROM photo_comment_view Where pID = @PhotoID" >
    4.     <SelectParameters>
    5.         <asp:ControlParameter Name="PhotoID" ControlID="FormView1" PropertyName="SelectedValue" Type="Int32"
    6.             DefaultValue="0" />
    7.     </SelectParameters>
    8. </asp:SqlDataSource>

    I hope it is useful.




     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 7, 2011 12:27 PM
  • User238457982 posted

    I tried your suggestion though not sure why you suggested this way. But your approach does not work. It compiles, but does not show out put.


    Do you know why I cannot pass this --> <%# Eval("PhotoID") %> information to selectcommand? Or do you or anyone likes to give any suggestion?


    <%# Eval("PhotoID") %> <---- This contains the photoID and prints it out in webpage. I just do not know how to put it in the select command. Please help or give suggestion.



    Friday, January 7, 2011 1:08 PM
  • User-1316079624 posted

    In your code, FormView1 is the data-bound control that is bound to ObjectDataSource1, so "<%# Eval("PhotoID") %>" should only be used to bind the PhotoID value to the controls that are inside the templates of the FormView1.

    Regarding my suggestion, the aim was to set FormView1.DataKeyNames = "PhotoID", so that FormView1.SelectedValue contains the PhotoID of the displayed record.

    Then used a ControlParameter to bind the value of a FormView1.SelectedValue (PhotoID) to a parameter that is used in a SQL query of the SqlDataSource1
    (I assumed that PhotoID is of type Int32; correct if I'm wrong).

    I hope I've achieved to explain my approach (sorry my english).


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 7, 2011 2:59 PM
  • User-1316079624 posted

    I had not seen the UpdatePanel1.
    It will be necessary to put the GridView1 within the UpdatePanel1, or within a new UpdatePanel (in this case, set FormView1 as trigger if UpdateMode="conditional").


     

    Friday, January 7, 2011 3:17 PM
  • User238457982 posted

    Hello,


    thank you for your response, but it does not work. I think that I have not explained you the scenerio. The website is the Personal template from Microsoft: http://msdn.microsoft.com/en-us/library/ms972963.aspx or you can find the project at

    http://msdn.microsoft.com/en-us/express/aa700818#personal or at

    http://msdn.microsoft.com/en-us/express/cc533486

    I want to add a comment feature with it. There is a PhotoManager Business object where the stored procedures get excuted. I added 1 method, GetComment(int PhotoID), for my comment feature, but the problem is: though I can display all comments but I cannot display comments about a specific picture. I think because I do not know how to access the PhotoID query String (not sure)?

    Some codes are attached. Is there any way I can capture the PhotoID from <%# Eval("PhotoID") %> and put it in an HTML control, say textbox or some hidden field and then access the hidden field's content to pass it as parameter for the sql select statement?


    Or do you know why I cannot pass PhotoID to the GetComment(int PhotoID) method? Do you have any other suggestion?

    <%@	Page Language="C#" MasterPageFile="~/Default.master" Title="Your Name Here | Picture Details"
    	CodeFile="Details.aspx.cs" Inherits="Details_aspx" %>
    
    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
    
    	<div class="shim solid"></div>
    	
    	<div class="page" id="details">
      
    		<asp:formview id="FormView1" runat="server"	datasourceid="ObjectDataSource1" cssclass="view"
    			borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true">
    			<itemtemplate>
    			
    				<div class="buttonbar buttonbar-top">
    					<a href="Albums.aspx"><asp:image ID="Image1" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton9" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton10"	Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton11"	Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton12"	Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
    				</div>
    				<p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
    				<table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
    					<tr>
    						<td class="topx--"></td>
    						<td class="top-x-"></td>
    						<td class="top--x"></td>
    					</tr>
    					<tr>
    						<td class="midx--"></td>
    						<td><img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" 
                            style="border:4px solid white" alt='Photo Number <%# Eval("PhotoID") %>' /></a></td>
    						<td class="mid--x"></td>
    					</tr>
    					<tr>
    						<td class="botx--"></td>
    						<td class="bot-x-"></td>
    						<td class="bot--x"></td>
    					</tr>
    				</table>
    				<p><a href='Download.aspx?AlbumID=<%# Eval("AlbumID") %>&Page=<%# Container.DataItemIndex %>'>
    					<asp:image runat="Server" id="DownloadButton" AlternateText="download this photo" skinid="download" /></a></p>
    				<div class="buttonbar">
    					<a href="Albums.aspx"><asp:image ID="Image2" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton2" Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton3" Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton4" Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
    				</div>
    
    			</itemtemplate>
    		</asp:formview>
            <hr />
            
            <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource2">
        	<itemtemplate>
            <%# Eval("pID") %><br />
           <strong> <%# Eval("UserName")%><br/></strong>
             <%# Eval("CommentDesc")%><br/>
    
            </itemtemplate>
        </asp:Repeater>
    	</div>
    
    	<asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager" 
    		SelectMethod="GetPhotos">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
    		</SelectParameters>
    	</asp:ObjectDataSource>
    
      
      <asp:ObjectDataSource ID="ObjectDataSource2" Runat="server" TypeName="PhotoManager"  
    		SelectMethod="GetComments">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="PhotoID" Type="Int32" QueryStringField="PhotoID"
                DefaultValue="0"/>
    		</SelectParameters>
             
            </asp:ObjectDataSource>
    </asp:content>
    -----------------
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Web;
    using System.Windows.Forms;
    
    public class PhotoManager {
    
    	// Photo-Related Methods
    
    	public static Stream GetPhoto(int photoid, PhotoSize size) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("GetPhoto", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@PhotoID", photoid));
    				command.Parameters.Add(new SqlParameter("@Size", (int)size));
    				bool filter = !(HttpContext.Current.User.IsInRole("Friends") || HttpContext.Current.User.IsInRole("Administrators"));
    				command.Parameters.Add(new SqlParameter("@IsPublic", filter));
    				connection.Open();
    				object result = command.ExecuteScalar();
    				try {
    					return new MemoryStream((byte[])result);
    				} catch {
    					return null;
    				}
    			}
    		}
    	}
    
    	public static Stream GetPhoto(PhotoSize size) {
    		string path = HttpContext.Current.Server.MapPath("~/Images/");
    		switch (size) {
    			case PhotoSize.Small:
    				path += "placeholder-100.jpg";
    				break;
    			case PhotoSize.Medium:
    				path += "placeholder-200.jpg";
    				break;
    			case PhotoSize.Large:
    				path += "placeholder-600.jpg";
    				break;
    			default:
    				path += "placeholder-600.jpg";
    				break;
    		}
    		return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
    	}
    
    	public static Stream GetFirstPhoto(int albumid, PhotoSize size) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("GetFirstPhoto", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@AlbumID", albumid));
    				command.Parameters.Add(new SqlParameter("@Size", (int)size));
    				bool filter = !(HttpContext.Current.User.IsInRole("Friends") || HttpContext.Current.User.IsInRole("Administrators"));
    				command.Parameters.Add(new SqlParameter("@IsPublic", filter));
    				connection.Open();
    				object result = command.ExecuteScalar();
    				try {
    					return new MemoryStream((byte[])result);
    				} catch {
    					return null;
    				}
    			}
    		}
    	}
    
    	public static List<Photo> GetPhotos(int AlbumID) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("GetPhotos", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));
    				bool filter = !(HttpContext.Current.User.IsInRole("Friends") || HttpContext.Current.User.IsInRole("Administrators"));
    				command.Parameters.Add(new SqlParameter("@IsPublic", filter));
    				connection.Open();
    				List<Photo> list = new List<Photo>();
    				using (SqlDataReader reader = command.ExecuteReader()) {
    					while (reader.Read()) {
    						Photo temp = new Photo(
    							(int)reader["PhotoID"],
    							(int)reader["AlbumID"],
    							(string)reader["Caption"]);
    						list.Add(temp);
    					}
    				}
    				return list;
    			}
    		}
    
    
    	}
        /*******/
      
    
        public static List<Comment> GetComments(int PhotoID)
        {
          // pID = 5;
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString))
            {
                using (SqlCommand command = new SqlCommand("GetComments", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new SqlParameter("@pID", PhotoID));
                    bool filter = !(HttpContext.Current.User.IsInRole("Friends") || HttpContext.Current.User.IsInRole("Administrators"));
                    command.Parameters.Add(new SqlParameter("@IsPublic", filter));
                    connection.Open();
                    List<Comment> list = new List<Comment>();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Comment temp = new Comment(
                                (string)reader["UserName"],
                                (string)reader["CommentDesc"],
                                (int)reader["pID"]);
                            list.Add(temp);
                        }
                    }
                    return list;
                }
            }
        }
    
    
    
    
        /**/
    
    	public static List<Photo> GetPhotos() {
    		return GetPhotos(GetRandomAlbumID());
    	}
    
    	public static void AddPhoto(int AlbumID, string Caption, byte[] BytesOriginal) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("AddPhoto", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));
    				command.Parameters.Add(new SqlParameter("@Caption", Caption));
    				command.Parameters.Add(new SqlParameter("@BytesOriginal", BytesOriginal));
    				command.Parameters.Add(new SqlParameter("@BytesFull", ResizeImageFile(BytesOriginal, 600)));
    				command.Parameters.Add(new SqlParameter("@BytesPoster", ResizeImageFile(BytesOriginal, 198)));
    				command.Parameters.Add(new SqlParameter("@BytesThumb", ResizeImageFile(BytesOriginal, 100)));
    				connection.Open();
    				command.ExecuteNonQuery();
    			}
    		}
    	}
    
    	public static void RemovePhoto(int PhotoID) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("RemovePhoto", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@PhotoID", PhotoID));
    				connection.Open();
    				command.ExecuteNonQuery();
    			}
    		}
    	}
    
    	public static void EditPhoto(string Caption, int PhotoID) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("EditPhoto", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@Caption", Caption));
    				command.Parameters.Add(new SqlParameter("@PhotoID", PhotoID));
    				connection.Open();
    				command.ExecuteNonQuery();
    			}
    		}
    	}
    
    	// Album-Related Methods
    
    	public static List<Album> GetAlbums() {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("GetAlbums", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				bool filter = !(HttpContext.Current.User.IsInRole("Friends") || HttpContext.Current.User.IsInRole("Administrators"));
    				command.Parameters.Add(new SqlParameter("@IsPublic", filter));
    				connection.Open();
    				List<Album> list = new List<Album>();
    				using (SqlDataReader reader = command.ExecuteReader()) {
    					while (reader.Read()) {
    						Album temp = new Album(
    							(int)reader["AlbumID"],
    							(int)reader["NumberOfPhotos"],
    							(string)reader["Caption"],
    							(bool)reader["IsPublic"]);
    						list.Add(temp);
    					}
    				}
    				return list;
    			}
    		}
    	}
    
    	public static void AddAlbum(string Caption, bool IsPublic) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("AddAlbum", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@Caption", Caption));
    				command.Parameters.Add(new SqlParameter("@IsPublic", IsPublic));
    				connection.Open();
    				command.ExecuteNonQuery();
    			}
    		}
    	}
    
    	public static void RemoveAlbum(int AlbumID) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("RemoveAlbum", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));
    				connection.Open();
    				command.ExecuteNonQuery();
    			}
    		}
    	}
    
    	public static void EditAlbum(string Caption, bool IsPublic, int AlbumID) {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("EditAlbum", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				command.Parameters.Add(new SqlParameter("@Caption", Caption));
    				command.Parameters.Add(new SqlParameter("@IsPublic", IsPublic));
    				command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));
    				connection.Open();
    				command.ExecuteNonQuery();
    			}
    		}
    	}
    
    	public static int GetRandomAlbumID() {
    		using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
    			using (SqlCommand command = new SqlCommand("GetNonEmptyAlbums", connection)) {
    				command.CommandType = CommandType.StoredProcedure;
    				connection.Open();
    				List<Album> list = new List<Album>();
    				using (SqlDataReader reader = command.ExecuteReader()) {
    					while (reader.Read()) {
    						Album temp = new Album((int)reader["AlbumID"], 0, "", false);
    						list.Add(temp);
    					}
    				}
    				try {
    					Random r = new Random();
    					return list[r.Next(list.Count)].AlbumID;
    				} catch {
    					return -1;
    				}
    			}
    		}
    	}
    
    	// Helper Functions
    
    	private static byte[] ResizeImageFile(byte[] imageFile, int targetSize) {
    		using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) {
    			Size newSize = CalculateDimensions(oldImage.Size, targetSize);
    			using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb)) {
    				using (Graphics canvas = Graphics.FromImage(newImage)) {
    					canvas.SmoothingMode = SmoothingMode.AntiAlias;
    					canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
    					canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
    					canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
    					MemoryStream m = new MemoryStream();
    					newImage.Save(m, ImageFormat.Jpeg);
    					return m.GetBuffer();
    				}
    			}
    		}
    	}
    
    	private static Size CalculateDimensions(Size oldSize, int targetSize) {
    		Size newSize = new Size();
    		if (oldSize.Height > oldSize.Width) {
    			newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
    			newSize.Height = targetSize;
    		} else {
    			newSize.Width = targetSize;
    			newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
    		}
    		return newSize;
    	}
    
    	public static ICollection ListUploadDirectory() {
    		DirectoryInfo d = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/Upload"));
    		return d.GetFileSystemInfos("*.jpg");
    	}
    
    }


    Saturday, January 8, 2011 2:58 AM
  • User-1316079624 posted

    By the code that you posted above, will be passed as parameter to the method GetComments the value of query string PhotoID.

    So to open the page in the album 1, with the comments of the photo 5, you would have to open the page as follows:


    1. http://........./Details.aspx?AlbumID=1&PhotoID=5


    To pass the value of a control inside of this page, you should use a ControlParameter instead of a QueryStringParameter.

    If the intention is to pass the PhotoID, the record displayed in FormView1, try to make the changes that I described in my first reply.

    Only for testing, add two labels (eg: lblPhotoID1 and lblPhodoID2) to your page, and then try the following:


    - add an FormView1.OnDataBound event handler with the following code:
     
     

    1. lblPhotoID1.Text = FormView1.SelectedValue.ToString();


    -  add an ObjectDataSource2.OnSelecting event handler:


    1. lblPhotoID2.Text = e.InputParameters.Values[0];


    lblPhotoID1 should display the PhotoID which is in FormView1.SelectedValue
    lblPhotoID2 should display the PhotoID which is being sent as a parameter.


    I hope this help.

     

    Saturday, January 8, 2011 9:50 AM
  • User238457982 posted

    Hello,

    thank you for your response and it works. I can now display comments about a specific picture,
    and I get the QueryString from the url that gets generated from Photos.aspx.

    In Photos.aspx, this line generates the query string for details.aspx:

    <td><a href='Details.aspx?AlbumID=<%# Eval("AlbumID") %>&PhotoID=<%# Eval("PhotoID") %>'>
                                <img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" style="border:4px solid white" alt='Thumbnail of Photo Number <%# Eval("PhotoID") %>' /></a></td>


    and then in details.aspx, the image with its comments get showed. However, I have faced a new problem, which is:

    While I browse the image with image button or the pager links, the url does not get modified. For example,
    say I selected at Photos.aspx photo #7 from Album # 6. Then, the new url is:


    http://localhost:64570/PersonalWebSiteCSharp/Details.aspx?AlbumID=6&PhotoID=7

    And the comments get displayed for Photo# 7

    However, when I go to next image or previous image either with the aid of imagebutton or pager links, the url does not get modified to:


    http://localhost:64570/PersonalWebSiteCSharp/Details.aspx?AlbumID=6&PhotoID=8 or
    http://localhost:64570/PersonalWebSiteCSharp/Details.aspx?AlbumID=6&PhotoID=9

    As a result, I cannot see the comments of the selected photo as the url stays unchanged.

    How to change the url with a new "PhotoID" QueryString as I or the User goes to next or previous or browse
    through photos either by ImageButton or by the Pager Links?


    I made a YouTube video about this problem. The YouTube video's link is at:

    http://www.youtube.com/watch?v=ISDQiqvpuQg

    How can I change the url with a new PhotoID QueryString as the User goes to next or previous or browse through photos
    either by ImageButton or by the Pager Links?


    <%@	Page Language="C#" MasterPageFile="~/Default.master" Title="Your Name Here | Photos"
    	CodeFile="Photos.aspx.cs" Inherits="Photos_aspx" %>
    
    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
    	
    	<div class="shim solid"></div> 
    	  
    	<div class="page" id="photos">
    		<div class="buttonbar buttonbar-top">
    			<a href="Albums.aspx"><asp:image ID="Image1" runat="Server" skinid="gallery" /></a>
    		</div>
    		<asp:DataList ID="DataList1" runat="Server"	cssclass="view"	dataSourceID="ObjectDataSource1" 
    			repeatColumns="4" repeatdirection="Horizontal" onitemdatabound="DataList1_ItemDataBound" EnableViewState="false">
    			<ItemTemplate>
    				<table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
    					<tr>
    						<td class="topx--"></td>
    						<td class="top-x-"></td>
    						<td class="top--x"></td>
    					</tr>
    					<tr>
    						<td class="midx--"></td>
    						<td><a href='Details.aspx?AlbumID=<%# Eval("AlbumID") %>&PhotoID=<%# Eval("PhotoID") %>'>
    							<img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" style="border:4px solid white" alt='Thumbnail of Photo Number <%# Eval("PhotoID") %>' /></a></td>
    						<td class="mid--x"></td>
    					</tr>
    					<tr>
    						<td class="botx--"></td>
    						<td class="bot-x-"></td>
    						<td class="bot--x"></td>
    					</tr>
    				</table>
    				<p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
    			</ItemTemplate>
    			<FooterTemplate>
    			</FooterTemplate>
    		</asp:DataList>
    		<asp:panel id="Panel1" runat="server" visible="false" CssClass="nullpanel">There are currently no pictures in this album.</asp:panel>
    		<div class="buttonbar">
    			<a href="Albums.aspx"><asp:image id="gallery" runat="Server" skinid="gallery" /></a>
    		</div>
    	</div>
    	
    	<asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager" 
    		SelectMethod="GetPhotos">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
    		</SelectParameters>
    	</asp:ObjectDataSource>
    	
    </asp:content>
    ---------------------------------------------------------------------
    <%@	Page Language="C#" MasterPageFile="~/Default.master" Title="Your Name Here | Picture Details"
    	CodeFile="Details.aspx.cs" Inherits="Details_aspx" %>
    
    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
    
    	<div class="shim solid"></div>
    	
    	<div class="page" id="details">
      
    		<asp:formview id="FormView1" runat="server"	datasourceid="ObjectDataSource1" cssclass="view" 
    			borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true">
    			<itemtemplate>
    			
    				<div class="buttonbar buttonbar-top">
    					<a href="Albums.aspx"><asp:image ID="Image1" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton9" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton10"	Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton11"	Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton12"	Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
    				</div>
    				<p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
    				<table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
    					<tr>
    						<td class="topx--"></td>
    						<td class="top-x-"></td>
    						<td class="top--x"></td>
    					</tr>
    					<tr>
    						<td class="midx--"></td>
    						<td><img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" 
                            style="border:4px solid white" alt='Photo Number <%# Eval("PhotoID") %>' /></a></td>
    						<td class="mid--x"></td>
    					</tr>
    					<tr>
    						<td class="botx--"></td>
    						<td class="bot-x-"></td>
    						<td class="bot--x"></td>
    					</tr>
    				</table>
    				<p><a href='Download.aspx?AlbumID=<%# Eval("AlbumID") %>&Page=<%# Container.DataItemIndex %>'>
    					<asp:image runat="Server" id="DownloadButton" AlternateText="download this photo" skinid="download" /></a></p>
    				<div class="buttonbar">
    					<a href="Albums.aspx"><asp:image ID="Image2" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton2" Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton3" Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton4" Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
                        <br />
                          <br />
                        <asp:Label ID="TESTLABEL" runat="server" Text="HELLO" ForeColor="Cyan" Width="200" Height="300"></asp:Label>
    				</div>
    
    			</itemtemplate>
    		</asp:formview>
            <hr />
            
            <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource2">
        	<itemtemplate>
            PhotoID: <%# Eval("pID") %><br />
           <strong> User Name: <%# Eval("UserName")%><br/></strong>
             <%# Eval("CommentDesc")%><br/>
             ----------------------------------------<br />
    
            </itemtemplate>
        </asp:Repeater>
    
    
    	</div>
    
    	<asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager" 
    		SelectMethod="GetPhotos">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
    		</SelectParameters>
    	</asp:ObjectDataSource>
    
      
      <asp:ObjectDataSource ID="ObjectDataSource2" Runat="server" TypeName="PhotoManager"  
    		SelectMethod="GetComments">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="PhotoID" Type="Int32" QueryStringField="PhotoID"
                DefaultValue="0"/>
    		</SelectParameters>
             
            </asp:ObjectDataSource>
    </asp:content>
    -------------------------------------------------------------------------
    using System;
    using System.Data;
    using System.Configuration;
    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;
    using System.Windows.Forms;
    
    
    public partial class Details_aspx : System.Web.UI.Page {
    
        void Page_Load(object sender, EventArgs e) {
    		Page.MaintainScrollPositionOnPostBack = true;
            if (!IsPostBack) {
                 int i = Convert.ToInt32(Request.QueryString["PhotoID"]);
                if (i >= 0) FormView1.PageIndex = i;
            }
        }
        
    }


    Saturday, January 8, 2011 1:30 PM
  • User-1316079624 posted


    To change the url, try:


    1. <asp:formview id="FormView1" runat="server" datasourceid="ObjectDataSource1" cssclass="view"  
    2.     borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true"
    3.     DataKeyNames="PhotoID" >  


    and add this code in the FormView1.OnPageIndexChanged event handler:

     

    1. Response.Redirect("~/Details.aspx?AlbumID=" +
    2.                               Request.QueryString["AlbumID"] + 
    3.                               "&PhotoID=" +
    4.                               FormView1.SelectedValue.ToString());



    Sorry for the insistence, but if you used a ControlParameter instead of a QueryStringParameter to pass the PhotoID

    through FormView1.SelectedValue was not necessary to add this code.

    I hope this help.

     

    Saturday, January 8, 2011 6:48 PM
  • User238457982 posted

    Hello silvioyf,

    thank you a lot. You suggested me to use

    - add an FormView1.OnDataBound event handler with the following code:
     
       1. lblPhotoID1.Text = FormView1.SelectedValue.ToString();

    I did, and it is working. Please see the new You Tube video:

    http://www.youtube.com/watch?v=FWfgYr1W2C4

    You also said,

    ---  add an ObjectDataSource2.OnSelecting event handler:


       1. lblPhotoID2.Text = e.InputParameters.Values[0];

    This does not work; I get compile error like:

    Cannot apply indexing with [] to an expression of type 'System.Collections.ICollection'

    --------------------------------------------------------------------------------------------------
    The main problem is this:


    The problem is this:

    as the image changes after I use the pager link or prev/next button, sometimes the
    respective photo's comment does not appear. I often have to click it twice. Please see the new You Tube video:

    http://www.youtube.com/watch?v=FWfgYr1W2C4


    Just to let you know that ---- The Table Adapter image is photo# 7, the VBDOTNET image is photo# 8, the
    SQLError image is photo# 9, the GridView image is photo# 10.

    Please suggest if you can.


    <%@	Page Language="C#" MasterPageFile="~/Default.master" Title="Your Name Here | Picture Details"
    	CodeFile="Details.aspx.cs" Inherits="Details_aspx" %>
    
    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
    
    	<div class="shim solid"></div>
    	
    	<div class="page" id="details">
      <script runat="server">
    
      void FormView_ItemCreated(Object sender, EventArgs e)
      {
        Label1.Text = "The key value is " + FormView1.SelectedValue.ToString() + ".";
       // Response.Redirect(@"http://localhost:64570/PersonalWebSiteCSharp/Details.aspx?AlbumID=6&PhotoID="+FormView1.SelectedValue.ToString());
      }
     /** void EVNT(object sender, ObjectDataSourceSelectingEventArgs e) 
      {
          Label2.Text = e.InputParameters.Values["PhotoID"];
      }**/
    
    </script>
    
    		<asp:formview id="FormView1" runat="server"	datasourceid="ObjectDataSource1" cssclass="view" 
    			borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" datakeynames="PhotoID"
    
                EnableViewState="false" AllowPaging="true" onitemcreated="FormView_ItemCreated"  
    >
    			<itemtemplate>
                  
    				<div class="buttonbar buttonbar-top">
    					<a href="Albums.aspx"><asp:image ID="Image1" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton9" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton10"	Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton11"	Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton12"	Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
    				</div>  
    				<p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
    				<table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
    					<tr>
    						<td class="topx--"></td>
    						<td class="top-x-"></td>
    						<td class="top--x"></td>
    					</tr>
    					<tr>
    						<td class="midx--"></td>
    						<td><img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" 
                            style="border:4px solid white" alt='Photo Number <%# Eval("PhotoID") %>' /></a></td>
    						<td class="mid--x"></td>
    					</tr>
    					<tr>
    						<td class="botx--"></td>
    						<td class="bot-x-"></td>
    						<td class="bot--x"></td>
    					</tr>
    				</table>
    				<p><a href='Download.aspx?AlbumID=<%# Eval("AlbumID") %>&Page=<%# Container.DataItemIndex %>'>
    					<asp:image runat="Server" id="DownloadButton" AlternateText="download this photo" skinid="download" /></a></p>
    				<div class="buttonbar">
    					<a href="Albums.aspx"><asp:image ID="Image2" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton2" Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton3" Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton4" Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
                        <br />
                          <br />
                       </div>
    
    			</itemtemplate>
    		</asp:formview>
             <asp:Label ID="Label1" runat="server"  ForeColor="Cyan" Width="200" Height="20"></asp:Label>
    		  <asp:Label ID="Label2" runat="server"  ForeColor="Cyan" Width="200" Height="20"></asp:Label>		
            <hr />   <hr />
            
           <asp:Repeater ID="Repeater2" runat="server" DataSourceID="SqlDataSource1">
        	<itemtemplate>
           <b>Photo ID: </b><span style="color:Cyan;"> <%# Eval("pID")%></span><br/>
           <strong> User Name: <%# Eval("UserName")%><br/></strong>
             <%# Eval("CommentDesc")%><br/>
             ----------------------------------------<br />
    
            </itemtemplate>
        </asp:Repeater>
    
    	</div>
    
    	
    <asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager"   
    		SelectMethod="GetPhotos">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
               
    		</SelectParameters>
    	</asp:ObjectDataSource>
    
     <asp:SqlDataSource ID="SqlDataSource1" runat="server"
           ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>"
          SelectCommand="SELECT UserName, commentDesc, pID FROM photo_comment_view Where pID = @PhotoID" >
           <SelectParameters>
             <asp:ControlParameter Name="PhotoID" ControlID="FormView1" PropertyName="SelectedValue" Type="Int32"
                   DefaultValue="0" />
          </SelectParameters>
       </asp:SqlDataSource>
    </asp:content>
    
    
    
    -----------------------------------------------------------------------------------
    using System;
    using System.Data;
    using System.Configuration;
    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;
    using System.Windows.Forms;
    
    
    public partial class Details_aspx : System.Web.UI.Page {
    
        void Page_Load(object sender, EventArgs e) {
    		Page.MaintainScrollPositionOnPostBack = true;
            if (!IsPostBack) {
                 int i = Convert.ToInt32(Request.QueryString["PageID"]);
                if (i >= 0) FormView1.PageIndex = i;
            }
        }
    
    
    
    
       
    }



    Saturday, January 8, 2011 9:08 PM
  • User238457982 posted

    I am just reading your comment and suggestion. Thank you again. I am going to go over  this  solution of yours and will update you here.


    Saturday, January 8, 2011 9:19 PM
  • User-1316079624 posted

    About Label1, use the FormView.DataBound event handler instead of FormView.ItemCreated, because the ItemCreated 

    event occurs before the FormView control is bound to data (see note on this page).


    About Label2 with SqlDataSource control, add in the SqlDataSource.OnSelecting event handler:

     

    1. Label2.Text = e.Command.Parameters["@PhotoID"].Value.ToString();


    I hope this help.


    Saturday, January 8, 2011 10:17 PM
  • User238457982 posted

    Hello,


    thank you for your response. I have tried your suggestion again, but the page does not get redirected. I get an error from the browser like:

    The page isn't redirecting properly....

    I went to debug mode and saw FormView1.SelectedValue.ToString() or  e.Command.Parameters["@PhotoID"].Value.ToString()


    value is always 7 and never changes to the next value. As a result the page is not updating with new information or does not redirect.

    Below are two different Details.aspx where I have tried different approaches per your suggestion, but neither works: either 

    the url does not change or browser cannot redirect.


    This YouTube video will show the problem:

    http://www.youtube.com/watch?v=QKJ7-Hjy_ks


    Please suggest.

    <%@	Page Language="C#" MasterPageFile="~/Default.master" Title="Your Name Here | Picture Details"
    	CodeFile="Details.aspx.cs" Inherits="Details_aspx" %>
    
    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
    
    	<div class="shim solid"></div>
    	
    	<div class="page" id="details">
      <script runat="server">
      void PageIndexChanged(Object sender, EventArgs e){
    
       Response.Redirect(@"http://localhost:64570/PersonalWebSiteCSharp/Details.aspx?AlbumID=6&PhotoID="+FormView1.SelectedValue.ToString());
      }
        void FormViewBoundData(object sender, EventArgs e)
        {
          Label1.Text = "The key value is for SelectedValue from FormView= " + FormView1.SelectedValue.ToString() + ".";
        }
        void SQLData_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
        Label2.Text = "The key value is for PhotoID from SQLDATA_ONSelecting=  " + e.Command.Parameters["@PhotoID"].Value.ToString();
    
        }
    
    </script>
    
    		<asp:formview id="FormView1" runat="server"	datasourceid="ObjectDataSource1" cssclass="view" 
    			borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" datakeynames="PhotoID"
    
                EnableViewState="false" AllowPaging="true" 
                 ondatabound="FormViewBoundData"  OnPageIndexChanged="PageIndexChanged"
    >
    			<itemtemplate>
                  
    				<div class="buttonbar buttonbar-top">
    					<a href="Albums.aspx"><asp:image ID="Image1" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton9" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton10"	Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton11"	Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton12"	Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
    				</div>  
    				<p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
    				<table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
    					<tr>
    						<td class="topx--"></td>
    						<td class="top-x-"></td>
    						<td class="top--x"></td>
    					</tr>
    					<tr>
    						<td class="midx--"></td>
    						<td><img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" 
                            style="border:4px solid white" alt='Photo Number <%# Eval("PhotoID") %>' /></a></td>
    						<td class="mid--x"></td>
    					</tr>
    					<tr>
    						<td class="botx--"></td>
    						<td class="bot-x-"></td>
    						<td class="bot--x"></td>
    					</tr>
    				</table>
    				<p><a href='Download.aspx?AlbumID=<%# Eval("AlbumID") %>&Page=<%# Container.DataItemIndex %>'>
    					<asp:image runat="Server" id="DownloadButton" AlternateText="download this photo" skinid="download" /></a></p>
    				<div class="buttonbar">
    					<a href="Albums.aspx"><asp:image ID="Image2" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton2" Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton3" Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton4" Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
                        <br />
                          <br />
                       </div>
    
    			</itemtemplate>
    		</asp:formview>
             <asp:Label ID="Label1" runat="server"  ForeColor="Cyan" Width="200" Height="20"></asp:Label>
    			<asp:Label ID="Label2" runat="server"  ForeColor="Cyan" Width="200" Height="20"></asp:Label>	
            <hr />   <hr />
            
           <asp:Repeater ID="Repeater2" runat="server" DataSourceID="SqlDataSource1">
        	<itemtemplate>
           <span style="color:Cyan;"> <%# Eval("pID")%></span><br/>
           <strong> User Name: <%# Eval("UserName")%><br/></strong>
             <%# Eval("CommentDesc")%><br/>
             ----------------------------------------<br />
    
            </itemtemplate>
        </asp:Repeater>
    
    	</div>
    
    	<asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager"  
    		SelectMethod="GetPhotos">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
               
    		</SelectParameters>
    	</asp:ObjectDataSource>
    
     <asp:SqlDataSource ID="SqlDataSource1" runat="server"
           ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>" OnSelecting="SQLData_Selecting"
          SelectCommand="SELECT UserName, commentDesc, pID FROM photo_comment_view Where pID = @PhotoID" >
           <SelectParameters>
             <asp:ControlParameter Name="PhotoID" ControlID="FormView1" PropertyName="SelectedValue" Type="Int32"
                   DefaultValue="0" />
          </SelectParameters>
       </asp:SqlDataSource>
    </asp:content>
    
    
    
    --------------------------------
    


    Sunday, January 9, 2011 12:27 AM
  • User-1316079624 posted

    About the approach using QueryStringParameter and Response.Redirect, I did some testing and

    FormView.SelectedValue property is not available at the event FormView.OnPageIndexChanged,

    so really sorry but that code will not work. I believe that using this approach will be complicated.


    About the approach using ControlParameter:


    - remove the FormView1.OnPageIndexChanged event handler;

    - this approach will not change the url

    - just to confirm, you removed the UpdatePanel's, right?

    - I do not know if this could be causing problems, but put the "event handler's" in the Details.aspx.cs

    instead Details.aspx, something like this:


    1. public partial class Details : System.Web.UI.Page
    2.  
    3.     protected void Page_Load(object sender, EventArgs e)
    4.     {
    5.     }
    6.  
    7.     protected void FormViewBoundData(object sender, EventArgs e)  
    8.     {  
    9.         Label1.Text = "The key value is for SelectedValue from FormView= " + FormView1.SelectedValue.ToString() + ".";  
    10.     }  
    11.  
    12.     protected void SQLData_Selecting(object sender, SqlDataSourceSelectingEventArgs e)  
    13.     {  
    14.         Label2.Text = "The key value is for PhotoID from SQLDATA_ONSelecting= " + e.Command.Parameters["@PhotoID"].Value.ToString();  
    15.     }  
    16.  
    17. }



    Try retesting. I'm finding it strange the value of Label1 and Label2 not change ...

     

    I hope this help.


    Sunday, January 9, 2011 12:29 PM
  • User238457982 posted

    Hello silvioyf,

    thank you a lot for taking so much of your time to help, but I believe that I have solved my problem per your older suggestions.

    [b]The Scenerios is:[/b]

    add a comment table which has bind with Photo table of personal starter site. Each photos have their own respective comments.when a person selects a photo, show the associated comments, if there were any.

    [b]My problem was:[/b]

    how to get the photoID so that I can show the associated comment(s).

    [b]Solution:[/b]

    in FormView control, state that that the datakey is PhotoID and in ObjectDataSource, specify that
    PhotoID as ControlParameter.

    The whole code of that aspx file is attached along with a new YouTube video about this problem, which is now solved.

    YouTube video link:

    ProblemSolvedVideo

    <%@	Page Language="C#" MasterPageFile="~/Default.master" Title="Your Name Here | Picture Details"
    	CodeFile="Details.aspx.cs" Inherits="Details_aspx" %>
    
    <asp:content id="Content1" contentplaceholderid="Main" runat="server">
    
    	<div class="shim solid"></div>
    	
    	<div class="page" id="details">
      
    		<asp:formview id="FormView1" runat="server"	datasourceid="ObjectDataSource1" cssclass="view"  DataKeyNames="PhotoID"
    			borderstyle="none" borderwidth="0" CellPadding="0" cellspacing="0" EnableViewState="false" AllowPaging="true">
    			<itemtemplate>
    			
    				<div class="buttonbar buttonbar-top">
    					<a href="Albums.aspx"><asp:image ID="Image1" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton9" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton10"	Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton11"	Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton12"	Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
    				</div>
    				<p><%# Server.HtmlEncode(Eval("Caption").ToString()) %></p>
    				<table border="0" cellpadding="0" cellspacing="0" class="photo-frame">
    					<tr>
    						<td class="topx--"></td>
    						<td class="top-x-"></td>
    						<td class="top--x"></td>
    					</tr>
    					<tr>
    						<td class="midx--"></td>
    						<td><img src="Handler.ashx?PhotoID=<%# Eval("PhotoID") %>&Size=S" class="photo_198" 
                            style="border:4px solid white" alt='Photo Number <%# Eval("PhotoID") %>' /></a></td>
    						<td class="mid--x"></td>
    					</tr>
    					<tr>
    						<td class="botx--"></td>
    						<td class="bot-x-"></td>
    						<td class="bot--x"></td>
    					</tr>
    				</table>
    				<p><a href='Download.aspx?AlbumID=<%# Eval("AlbumID") %>&Page=<%# Container.DataItemIndex %>'>
    					<asp:image runat="Server" id="DownloadButton" AlternateText="download this photo" skinid="download" /></a></p>
    				<div class="buttonbar">
    					<a href="Albums.aspx"><asp:image ID="Image2" runat="Server"	 skinid="gallery" /></a>
    					    
    					<asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Page" CommandArgument="First" skinid="first"/>
    					<asp:ImageButton ID="ImageButton2" Runat="server" CommandName="Page" CommandArgument="Prev" skinid="prev"/>
    					<asp:ImageButton ID="ImageButton3" Runat="server" CommandName="Page" CommandArgument="Next" skinid="next"/>
    					<asp:ImageButton ID="ImageButton4" Runat="server" CommandName="Page" CommandArgument="Last" skinid="last"/>
                        <br />
                          <br />
                    
    				</div>
                       <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource2">
        	<itemtemplate>
            PhotoID: <%# Eval("pID") %><br />
           <strong> User Name: <%# Eval("UserName")%><br/></strong>
             <%# Eval("CommentDesc")%><br/>
             ----------------------------------------<br />
    
            </itemtemplate>
        </asp:Repeater>
    
    
    			</itemtemplate>
    		</asp:formview>
            <hr />
            
         
    	</div>
    
    	<asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="PhotoManager" 
    		SelectMethod="GetPhotos">
    		<SelectParameters>
    			<asp:QueryStringParameter Name="AlbumID" Type="Int32" QueryStringField="AlbumID" DefaultValue="0"/>
    		</SelectParameters>
    	</asp:ObjectDataSource>
    
      
      <asp:ObjectDataSource ID="ObjectDataSource2" Runat="server" TypeName="PhotoManager"  
    		SelectMethod="GetComments">
    		<SelectParameters>
    		
                   <asp:ControlParameter Name="PhotoID" ControlID="FormView1" PropertyName="SelectedValue" Type="Int32"
                   DefaultValue="0" />
    		</SelectParameters>
             
            </asp:ObjectDataSource>
    </asp:content>
    ---------------------------------------------------------------------------
    using System;
    using System.Data;
    using System.Configuration;
    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 Details_aspx : System.Web.UI.Page
    {
    
        void Page_Load(object sender, EventArgs e)
        {
            Page.MaintainScrollPositionOnPostBack = true;
            if (!IsPostBack)
            {
                int i = Convert.ToInt32(Request.QueryString["Page"]);
                if (i >= 0) FormView1.PageIndex = i;
            }
        }
    
    }



    Sunday, January 9, 2011 12:36 PM