Solved

Session Variables in aspx and gridview

Posted on 2009-05-15
20
957 Views
Last Modified: 2012-05-07
Hi

Can someone help with setting a session variable in the attached code snippet.
 Session("xmlfile") = .......................................
Thanks
<ItemTemplate>

                        <asp:HyperLink ID="FileLink" NavigateUrl='<%# "LabelsEdit.aspx" + Container.DataItem.ToString() %>'

                            Text='<%# Container.DataItem.ToString() %>' runat="server" Target="_self" />

                    </ItemTemplate>

Open in new window

0
Comment
Question by:conceptdata
  • 9
  • 6
  • 3
  • +1
20 Comments
 
LVL 8

Expert Comment

by:Faheem Shaikh
Comment Utility
0
 

Author Comment

by:conceptdata
Comment Utility
Okay, but In my code I need ( didn't explain before) to set the session("xmlfile") to the value from Container.DataItem.ToString()...

Can you give a hint or better, some code ..
0
 
LVL 39

Expert Comment

by:abel
Comment Utility
The code you posted will be called for each item in the list. Setting the session to the current item will have the effect of the session containing only the last item in the (repeater/gridview/etc). Is that what you were after?
0
 

Author Comment

by:conceptdata
Comment Utility
I give you the whole code :


    <form id="form1" runat="server" method="post" name="LabelsNavigate">

    <div>

        <asp:Label ID="labelStatus" runat="server"></asp:Label><br />

        <asp:FileUpload ID="FileUpload1" runat="server" visible="false"/><br />

        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" visible="false" /><br /> 

        <br />

        <asp:GridView ID="GridView1" runat="server" DataSource="<%# GetUploadList() %>" OnRowDeleting="GridView1_RowDeleting"

            AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" 

            GridLines="None">

            <RowStyle BackColor="#EFF3FB" />

            <Columns>

                <asp:TemplateField HeaderText="Choose data-file">

                    <ItemStyle HorizontalAlign="Center" Width="70%" />

                    <ItemTemplate>

                        <asp:HyperLink ID="FileLink" NavigateUrl='<%# "LabelsEdit.aspx" + Container.DataItem.ToString() %>'

                            Text='<%# Container.DataItem.ToString() %>' runat="server" Target="_self" />

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Delete?" visible="false">

                    <ItemStyle HorizontalAlign="Center" Width="30%" />

                    <ItemTemplate>

                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"

                            OnClientClick='return confirm("Are you sure you want to delete this entry?");'

                            Text="Delete?" visible="false" />

                    </ItemTemplate>

                </asp:TemplateField>
 

            </Columns>

            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <EditRowStyle BackColor="#2461BF" />

            <AlternatingRowStyle BackColor="White" />

        </asp:GridView>

    </div>

    </form>

Open in new window

0
 
LVL 11

Expert Comment

by:b_levitt
Comment Utility
You would need to use the DataGrid.OnItemDataBound event.  However, I'm not sure that your question makes sense - Container.DataItem exists for EACH item in the collection that your data grid is bound too.  Even if I gave you the code to do it, you only have a single session variable for potentially multiple items.

What are you trying to accomplish?
0
 
LVL 8

Expert Comment

by:Faheem Shaikh
Comment Utility
Agree with b_levitt.
Something like this in the ItemBound event:
<% Session["xmlfile"] =
DataBinder.Eval(Container.DataItem, "playerID") %>  
Have a look at this link as well:
http://www.velocityreviews.com/forums/t89335-assign-value-from-datagrid-to-a-session-variable.html
 
0
 
LVL 11

Expert Comment

by:b_levitt
Comment Utility
I'm not sure what faheem is doing in his example - OnItemDataBound is an event, yet he has inline code in his example.

But in any case I don't want to go down that road until I understand what you're trying to do.
0
 
LVL 39

Expert Comment

by:abel
Comment Utility
the code of faheem will not work (tiny bug), because Container is not available once you are using normal code expression (i.e., outside <%#... %>, and inside <% ... %>). This would work, though:

<%# Session["xmlfile"] = DataBinder.Eval(Container.DataItem, "playerID"); %>
but like I said before, it will not have the effect you are after, which was seconded by b_levitt and faheem...
0
 
LVL 39

Expert Comment

by:abel
Comment Utility
What it seems that you want to accomplish is to keep a reference to some object, but you do not want to make that visible to the end-user, and it is a different object for each row. You can accomplish that by doing the following and whenever you need it, you can use the usual FindControl technique to get your data from the hidden field:

<asp:HiddenField runat="server" ID="xmlfile" Value="<%# Container.DataItem.ToString() %>" />
BUT! Looking again at your code, you seem to want to redirect the user to some other page and send the current dataitem along. That's easy, try the following instead, and use:

Dim selectedXmlFile As String = Request.QueryString("xmlfile")
inside your LabelsEdit.aspx to get the selected xmlfile.

<asp:HyperLink ID="FileLink" 

    NavigateUrl='<%# "LabelsEdit.aspx?xmlfile" + Container.DataItem.ToString() %>'

    Text='<%# Container.DataItem.ToString() %>' 

    runat="server" Target="_self" />

Open in new window

0
 
LVL 39

Expert Comment

by:abel
Comment Utility
small error not seen before posting. Use this instead (and you may need to UrlEscape it, I don't know what data is in there):

<asp:HyperLink ID="FileLink" 

    NavigateUrl='<%# "LabelsEdit.aspx?xmlfile=" + Container.DataItem.ToString() %>'

    Text='<%# Container.DataItem.ToString() %>' 

    runat="server" Target="_self" />

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 11

Expert Comment

by:b_levitt
Comment Utility
I appologize abel.  I didn't notice you had already informed the OP about the one-to-many problem with session and his DataItems.  At least we're all in agreement ;).
0
 
LVL 39

Expert Comment

by:abel
Comment Utility
no apologies needed, we're all on the same page and it is good to find out that one's "backed up" by others ;-)
0
 

Author Comment

by:conceptdata
Comment Utility
Hi Abel
I have thought about using URL passing variables.
But how do I GET the value on the next page in the "code Behind", and the use it in ALL the classes there ... ??

0
 
LVL 39

Expert Comment

by:abel
Comment Utility
> But how do I GET the value on the next page in the "code Behind"

I showed you that line already, here it is again, use it in the Page_Load event. You can put it into a property or do whatever you want with it.

Dim selectedXmlFile As String = Request.QueryString("xmlfile")
> and the use it in ALL the classes there

Create a property in the class (page) that receives the request. Say we call that property "XmlFile" and it is a string, then you can do this in the Page_Load:

XmlFile = Request.QueryString("xmlfile")
that's really all there is to it ;-)
0
 
LVL 39

Expert Comment

by:abel
Comment Utility
PS: any class that is run or called during a request/response cycle (which is basically anything you are doing), can use the Request object. So, it isn't that bad if you do not use a property and just use Request.QueryString("xmlfile"). You can call it anytime anywhere. Make note, that when someone accesses your page from somewhere else, that the string can be empty or Nothing.
0
 

Author Comment

by:conceptdata
Comment Utility
I'm getting this failure on your Dim line :

Non-invocable member 'System.Web.HttpRequest.QueryString' cannot be used like a method.      

protected void Page_Load(object sender, EventArgs e)
        {
            String selectedXmlFile = Request.QueryString("xmlfile");

            if (!IsPostBack)
            {
                BindGrid();
            }
        }
0
 

Author Comment

by:conceptdata
Comment Utility
Ok, now i'm getting it to work.
BUT I can't edit/update my xmldata in the gridview :
The sessionID that i'm using in my tmp-xmlfilename is changing on update.... an then it is no updated


     public String selectedXmlFile;

     public String selectedXmlFileTemp;

     public String RunOnce;

     protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                BindGrid();

            }
 

                selectedXmlFile = Server.MapPath("~/database/xmlfiles/" + Request.QueryString["xmlfile"]);

                selectedXmlFileTemp = Server.MapPath("~/database/xmlfiles/temp/" + Session.SessionID + Request.QueryString["xmlfile"]);

                File.Copy(selectedXmlFile, selectedXmlFileTemp);

            }

        }

Open in new window

0
 
LVL 39

Accepted Solution

by:
abel earned 500 total points
Comment Utility
> Non-invocable member 'System.Web.HttpRequest.QueryString' cannot be used like a method.  
   
apologies, you posted it the C# forum and I accidentally showed you VB code. Happen more often... :S. I see that by now you found out that (..) should be [...].

> The sessionID that i'm using in my tmp-xmlfilename is changing on update.... an then it is no updated

I am not following here. The SessionID is something you should not change, and not use directly (most of the time). The session id will remain the same on the same site by the same user using the same browser if it doesn't close his browser intermittently. The sessionid will change when time expires, when another browser or computer is chosen, when the browser is closed and reopened (not always) and when the user chooses so. If you want to store something per-user, use the userid (if you have something like that, i.e., from your database or login information).
0
 

Author Closing Comment

by:conceptdata
Comment Utility
I close. Point to abel
0
 
LVL 39

Expert Comment

by:abel
Comment Utility
What is that always when you try to understand askers and help them all the way through with extensive information and comments and then all you get is an undergrade? Please read the EE guidelines about the 10pts must principle. Remember, the expert trying to help you today you may need tomorrow.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now