Get filenotfoundexception using RadAsyncUpload - asp.net

i use the Telerik radasyncupload control like this:
Web.Config
<appSettings>
<add key="Telerik.AsyncUpload.TemporaryFolder" value="~/App_Data/RadUploadTemp" />
</appSettings>
ASP.NET
<telerik:RadAsyncUpload ID="rauIconUpload" runat="server" ChunkSize="0" Localization-Cancel="Löschen" Localization-Remove="Entfernen" Localization-Select="Auswählen"
Culture="de-DE" Skin="MetroTouch" TargetFolder="img/icons" MaxFileInputsCount="1">
</telerik:RadAsyncUpload>
<telerik:RadButton ID="rbtnIconUpload" runat="server" Text="Speichern" Skin="MetroTouch"></telerik:RadButton>
VB.NET
Private Sub rbtnIconUpload_Click(sender As Object, e As EventArgs) Handles rbtnIconUpload.Click
If rtxtIconBezeichnung.Text = String.Empty Or rtxtIconBezeichnung.Text = Nothing Or CHKValidation(rtxtIconBezeichnung.Text) = False Then
rnfUngueltigeEingabe.Visible = True
Else
Try
For Each f As UploadedFile In rauIconUpload.UploadedFiles
Dim img As New System.Drawing.Bitmap(f.InputStream)
Dim h As Integer = img.Height
Dim w As Integer = img.Width
img.Dispose()
Dim fileName As String = f.GetName()
IconPfad = "~/img/icons/" & fileName
If w = 16 And h = 16 Then
IconSize = "16x16"
ElseIf w = 32 And h = 32 Then
IconSize = "32x32"
Else
rnfIconNichtErzeugt.Visible = True
Exit For
End If
IconErzeugt = Datenzugriff.CRTNeuesIcon(rtxtIconBezeichnung.Text, IconPfad, rcbIconGruppe.SelectedValue, IconSize)
If IconErzeugt = True Then
rnfIconErzeugt.Visible = True
Page.ClientScript.RegisterClientScriptBlock([GetType](), "CloseScript", "redirectParentPage('IconVerwaltung.aspx')", True)
Else
rnfIconNichtErzeugt.Visible = True
End If
Next
Catch ex As Exception
rnfIconNichtErzeugt.Visible = True
End Try
End If
End Sub
If i try to use InputStream i get a filenotfoundexeption. I added a Screanshot of this error.
So, does someone have a idea what i'm doing wrong?
Thank you for reading.
Daniel

Try to remove the TargetFolder property from the markup:
<telerik:RadAsyncUpload ID="rauIconUpload" runat="server" ChunkSize="0" Localization-Cancel="Löschen" Localization-Remove="Entfernen" Localization-Select="Auswählen"
Culture="de-DE" Skin="MetroTouch" MaxFileInputsCount="1">
</telerik:RadAsyncUpload>
and save the file manually from in the click button event.

Related

Code to add items to a data grid is not working. Not sure whats wrong. I want to add all the columns into the gridview

My Public Class is Below:
public class GlobalVariable
public shared listbox2Count = listbox2.items.count
public shared containsListbox2Item
End Class
my code where i assign a text item to a variable object:
Public Function getListBoxText()
If ListBox2.Text = "X,Y Coordinate" Then
GlobalVariable.containsListBox2Item = "X,Y Coordinate"
ElseIf ListBox2.Text = "Latitude, Longitude" Then
GlobalVariable.containsListBox2Item = "Latitude, Longitude"
Return Nothing
End Function
My code where i am stuck is below:
Dim dt As New DataTable
dt.Clear()
For i As Integer = 0 To GlobalVariable.listbox2Count - 1
If GlobalVariable.containsListBox2Item(i) = "X,Y Coordinate" Then
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
ElseIf GlobalVariable.containsListBox2Item(i) = "Latitude, Longitude" Then
If (Not dt.Columns.Contains("Latitude")) Then dt.Columns.Add("Latitude")
If (Not dt.Columns.Contains("Longitude")) Then dt.Columns.Add("Longitude")
End If
Next
Dim mr As DataRow
mr = dt.NewRow
mr("X Coordinate") = "203910"
mr("Y Coordinate") = "190280"
mr("Latitude") = "100022"
mr("Longitude") = "201999"
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
I am absolutely not sure whats wrong with this code and if someone can help me or correct it for me would be great help Thanks. I want to add all four columns into the grid view. and then keep adding more and more columns using else if.
Try this, its extensive but it does work, it displays all the values you have on listbox2
Dim i As Integer
Dim dt As New DataTable
Dim Card As String = ""
Dim Geo As String = ""
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items.Item(i).Text = "X,Y Coordinate" Then
If Card = "ok" Then
Else
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
Card = "ok"
End If
ElseIf ListBox2.Items.Item(i).Text = "Latitude, Longitude" Then
If Geo = "ok" Then
Else
dt.Columns.Add("Latitude")
dt.Columns.Add("Longitude")
Geo = "ok"
End If
End If
Next
Dim mr As DataRow
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items.Item(i).Text.Contains(dt.Columns.Item(0).ToString.Substring(0, 1)) Then
If dt.Columns.Item(0).ToString = "Latitude" Then
mr = dt.NewRow
mr("Latitude") = "100909"
mr("Longitude") = "1002929"
ElseIf dt.Columns.Item(0).ToString = "X Coordinate" Then
mr = dt.NewRow
mr("X Coordinate") = "909090"
mr("Y Coordinate") = "109209"
End If
End If
If ListBox2.Items.Item(i).Text.Contains(dt.Columns.Item(2).ToString.Substring(0, 1)) Then
If dt.Columns.Item(2).ToString = "Latitude" Then
mr("Latitude") = "100909"
mr("Longitude") = "1002929"
ElseIf dt.Columns.Item(2).ToString = "X Coordinate" Then
mr("X Coordinate") = "909090"
mr("Y Coordinate") = "109209"
End If
End If
Dim res As Integer
res = i Mod 2
If res > 0 Or i = ListBox2.Items.Count - 1 Then
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
End If
Next
Simple Form that defines a GridView by using the contents of a ListBox to provide Column Information
Important I've altered the ListBox Values to represent Column Headers. See why below.
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox2" runat="server">
<asp:ListItem Text="X,Y Coordinate" Value="X Coordinate, Y Coordinate" />
<asp:ListItem Text="Latitude, Longitude" Value="Latitude, Longitude" />
</asp:ListBox>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
EmptyDataText="No Data" ShowHeader="true">
</asp:GridView>
</div>
</form>
Code Behind
Public Class WebForm1
Inherits System.Web.UI.Page
' DataTable Name and Application Cache Key
Const DataTableCacheKey As String = "CoordinatesDataTable"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Create the Table and add to Cache, only once
If Not Page.IsPostBack Then
CreateDataTableFromListView()
End If
GridView1.DataSource = Cache(DataTableCacheKey)
GridView1.DataBind()
End Sub
Create the DataSource
NOTE: By using the Value Property of the ListItem as a comma separated list of strings, you can associate multiple columns to a given Coordinate system. Note this is not the ideal way because there is no way set up a data type, I'm assuming everything is a Double value. Still it's far better than a long string of If conditions to determine columns and headers.
' All the magic happens here...
Private Sub CreateDataTableFromListView()
' Instantiate a DataTable with a table name
Dim dt As New DataTable(DataTableCacheKey)
' Loop throught the ListBox and...
For Each li As ListItem In ListBox2.Items
' Split each Value Property into an array
' of strings to use as Column identifiers
Dim ColumnHeaders() As String = li.Value.Split(",")
' Loop through the array of strings to create
' DataTable Columns
For Each ch As String In ColumnHeaders
dt.Columns.Add(ch, GetType(Double))
Next
Next
' Add an initial Blank Row
Dim row As DataRow = dt.NewRow()
' Loop Through Columns and set a default
' value of 0 for each column
For Each c As DataColumn In dt.Columns
row(c.ColumnName) = 0
Next
' Add the Row to the Table
dt.Rows.Add(row)
' Persist the DataTable to the Application cache
Cache(DataTableCacheKey) = dt
End Sub
End Class

Update statement in asp.net encountered with logic error?

I'm developing a project where user can can edit/update their profile, but somehow I found myself in trouble when try to update the data into Access Database. The only funniest thing is, ONLY profile picture is updated/change in database, but none for password, firstname, lastname, etc. The rest still the same. I hope someone can help me in this case, thanks in advance!
The Page Load:
If Not IsPostBack Then
DropDownList1.DataBind()
End If
LinkButtonCancel.Visible = False
FileuploadProfPic.Visible = False
TextBoxCfrmPassword.Visible = False
ButtonUpdateProf.Visible = False
TextBoxImage.Visible = False
LabelUpload.Visible = False
LabelCfnPss.Visible = False
TextBoxUsername.Enabled = False
TextBoxPassword.Enabled = False
TextBoxFirstName.Enabled = False
TextBoxLastName.Enabled = False
TextBoxEmail.Enabled = False
TextBoxHPN.Enabled = False
TextBoxUsername.ReadOnly = True
TextBoxPassword.ReadOnly = True
TextBoxFirstName.ReadOnly = True
TextBoxLastName.ReadOnly = True
TextBoxEmail.ReadOnly = True
TextBoxHPN.ReadOnly = True
UserData = Me.Data()
TextBoxUsername.Text = UserData.Username
TextBoxFirstName.Text = UserData.FirstName
TextBoxLastName.Text = UserData.LastName
TextBoxHPN.Text = UserData.MobileNumber
TextBoxEmail.Text = UserData.Email
ProfilePic.ImageUrl = UserData.ProfilePic
TextBoxImage.Text = UserData.ProfilePic
TextBoxPassword.Text = UserData.Password
The Data Function to call the data from database:
Dim dvLogin As DataView = CType(AccessDataSourceProfile.Select(DataSourceSelectArguments.Empty), DataView)
dvLogin.RowFilter = "Username = '" & DropDownList1.SelectedValue & "'"
Dim Dt As New UserLogin
Dt.Username = dvLogin(0)("Username").ToString
Dt.Password = dvLogin(0)("Password").ToString
Dt.FirstName = dvLogin(0)("FirstName").ToString
Dt.LastName = dvLogin(0)("LastName").ToString
Dt.MobileNumber = dvLogin(0)("MobileNumber").ToString
Dt.Email = dvLogin(0)("Email").ToString
Dt.ProfilePic = dvLogin(0)("ProfilePic").ToString
Return Dt
The Update Button:
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("Product.mdb") & ";Jet OLEDB:Database Password=;"
objConn.ConnectionString = strConnString
objConn.Open()
Dim savePath As String = "C:\Users\AdananLong\Documents\Visual Studio 2010\Projects\E-Commerce\E-Commerce\"
If (FileuploadProfPic.HasFile) Then
Dim files As String = FileuploadProfPic.FileName
savePath += files
FileuploadProfPic.SaveAs(savePath)
TextBoxImage.Text = files
Try
objCmd = New OleDbCommand("UPDATE Member SET [Password] = #password, FirstName = #firstname, LastName = #lastname, MobileNumber = #mobilenumber, Email = #email, ProfilePic = #profilepic WHERE Username = #username", objConn)
objCmd.Parameters.AddWithValue("#password", TextBoxPassword.Text)
objCmd.Parameters.AddWithValue("#firstname", TextBoxFirstName.Text)
objCmd.Parameters.AddWithValue("#lastname", TextBoxLastName.Text)
objCmd.Parameters.AddWithValue("#mobilenumber", TextBoxHPN.Text)
objCmd.Parameters.AddWithValue("#email", TextBoxEmail.Text)
objCmd.Parameters.AddWithValue("#profilepic", TextBoxImage.Text)
objCmd.Parameters.AddWithValue("#username", TextBoxUsername.Text)
objCmd.ExecuteNonQuery()
DropDownList1.DataBind()
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Update Sucessful."
Catch ex As Exception
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Cannot Update : Error (" & ex.Message & ")"
End Try
Else
Try
objCmd = New OleDbCommand("UPDATE Member SET [Password] = #password, FirstName = #firstname, LastName = #lastname, MobileNumber = #mobilenumber, Email = #email, ProfilePic = #profilepic WHERE Username = #username", objConn)
objCmd.Parameters.AddWithValue("#password", TextBoxPassword.Text)
objCmd.Parameters.AddWithValue("#firstname", TextBoxFirstName.Text)
objCmd.Parameters.AddWithValue("#lastname", TextBoxLastName.Text)
objCmd.Parameters.AddWithValue("#mobilenumber", TextBoxHPN.Text)
objCmd.Parameters.AddWithValue("#email", TextBoxEmail.Text)
objCmd.Parameters.AddWithValue("#profilepic", TextBoxImage.Text)
objCmd.Parameters.AddWithValue("#username", TextBoxUsername.Text)
objCmd.ExecuteNonQuery()
DropDownList1.DataBind()
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Update Sucessful."
Catch ex As Exception
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Cannot Update : Error (" & ex.Message & ")"
End Try
End If
objConn.Close()
objConn = Nothing
This seems to be a well know effect of forgetting to test for postbacks in the Page_Load code.
Every time your user triggers an event to be handled on the server (runat="server" and/or AutoPostBack="true" ) then the Page.Load event of your page is called BEFORE calling the event handler activated by the user action. See ASP.NET Life Cycle
This means that in your Page.Load code you should be careful to not reload the page controls with values from the database otherwise, when the event handler is started, you have the controls filled with the original values extracted in the Page.Load event.
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
.....
' code to load the controls with values from database
UserData = Me.Data()
TextBoxUsername.Text = UserData.Username
TextBoxFirstName.Text = UserData.FirstName
TextBoxLastName.Text = UserData.LastName
TextBoxHPN.Text = UserData.MobileNumber
TextBoxEmail.Text = UserData.Email
ProfilePic.ImageUrl = UserData.ProfilePic
TextBoxImage.Text = UserData.ProfilePic
TextBoxPassword.Text = UserData.Password
End If
End Sub

Looping through textboxes and labels

Im doing this project for an online test in ASP.NET in VB im using Microsoft visual studios 2012.
Im trying to get a loop going through my textboxes and check them against a word this will be change to be validated against a database to see if the answer are correct but when I do my loop I cannot get my text from the textbox.
Please see below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As Object
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Textboxname
TextboxText = textbox
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub
It looks like you are trying to use the string identifier of the control in place of the the actual control. Instead, you should take this identifier and search for the actual control on the page. You can do this using the FindControl method
Your function would therefore look something like (not compile tested):
Private Sub GoGoGo()
'
Dim oTextBox As TextBox
Dim oLabel As Label
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oTextBox = CType(Page.FindControl("TextQ" & CStr(check)), TextBox)
OTextBox.ReadOnly = True;
End If
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oLabel = CType(Page.FindControl("Label" & CStr(check)), Label)
oLabel.Visible = True
End If
If oTextBox.Text = "" Then
oLabel.Text = "no imput"
oLabel.ForeColor = Drawing.Color.Black
End If
If oTextBox.Text = "server" Then
oLabel.Text = "Correct"
oLabel.ForeColor = Drawing.Color.Green
End If
If oTextBox.Text = "Wrong" Then
oLabel.Text = "Wrong"
oLabel.ForeColor = Drawing.Color.Red
End If
Next
End Sub
Some notes:
You don't need all of those variables. Instead, just find the actual controls, and interact with the properties directly - just check the TextBox.Text value when you need to, and set the Label.text property directly. The set is especially important as you want to update the original control property so it is shown on the page.
Similarly, you don't need Number - you can use check as this is your loop counting variable.
Whether you use the + operator or the & operator for string concatenation is up to you. There's already a good question and several answers here.
You also don't need the exit condition for the loop - the loop will exit as soon as you reach MaxTime. If you want it to exit early, just vary your To condition (e.g. Currentloop To MaxTime - 1)
UPDATE:
Page.FindControl will only work with controls that are immediate children of the root element on the page. Instead, you should try calling FindControl recursively. You should also make sure that a control with the id TextQ1 exists - look in the HTML source for the page on the client to make sure a TextBox with this id exists.
There are many examples of this on the net. Here's a VB.Net version (source: http://www.pavey.me/2007/09/recursive-pagefindcontrol-for-vbnet.html) that you can add to your page:
Public Function FindControlRecursive(Of ItemType)(ByVal Ctrl As Object, ByVal id As String) As ItemType
If String.Compare(Ctrl.ID, id, StringComparison.OrdinalIgnoreCase) = 0 AndAlso TypeOf Ctrl Is ItemType Then
Return CType(Ctrl, ItemType)
End If
For Each c As Control In Ctrl.Controls
Dim t As ItemType = FindControlRecursive(Of ItemType)(c, id)
If t IsNot Nothing Then
Return t
End If
Next
Return Nothing
End Function
Your line in the code above would then become:
oTextBox = FindControlRecursive(of TextBox)(Page.Controls(0), "TextQ" & CStr(check))
You'd also need to do the same for the Label control.
It Look like you are using only name istead of textbox try with the code below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As TextBox
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Ctype(Me.Controls(Textboxname), TextBox)
TextboxText = textbox.Text
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub

OnSelectedIndexChanged not working first selection, but will on subsequent selections

I have a listbox in a datagrid that is supposed to update upon selection change, and it does, but not on first try. only after it has posted back, after the first time it is clicked will it work as intended. any help appreciated.
Here is the front end portion of the datagrid with the listbox.
<asp:TemplateColumn HeaderText="Qty">
<ItemStyle HorizontalAlign="Center" Wrap="False" CssClass="grid" />
<HeaderStyle HorizontalAlign="Center" ForeColor="Black" Font-Bold="true" CssClass="grid" width="30" />
<ItemTemplate>
<asp:ListBox ID="lstQty" rows="1" runat="server" AutoPostBack="True" EnableViewState="True" OnSelectedIndexChanged="lstQtyUpdate" />
</ItemTemplate>
</asp:TemplateColumn>
Here is the page load section:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not IsPostBack Then
LoadCart()
cartList.Columns(0).Visible = False
If (cartList.Items.Count = 0) Then
cartList.Visible = False
lblEmptyMsg.Visible = True
Else
cartList.Visible = True
lblEmptyMsg.Visible = False
End If
End If
Catch ex As Exception
Errorlog(ex, "Cart.Page_Load()")
End Try
End Sub
This is the sub that is called with the onselectedindexchanged:
Protected Sub lstQtyUpdate(sender As Object, e As System.EventArgs)
Dim lb As New ListBox
lb = CType(sender, ListBox)
Dim thisID As String = lb.ClientID
Dim oiQty As Integer = ComFunctions.ConvertToInt(lb.SelectedItem.Value)
Dim oiID As Integer = 0
For Each item As DataGridItem In cartList.Items
lb = CType(item.FindControl("lstQty"), ListBox)
If (thisID = lb.ClientID) Then
oiID = ComFunctions.ConvertToInt(item.Cells(0).Text)
Exit For
End If
Next.....
Here is the binding for the datagrid, which may be the culprit.
Private Sub cartList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles cartList.ItemDataBound
Try
Dim rbd As ImageButton
Dim lst As ListBox
Dim id As Integer = 0
Dim evTitle As String = String.Empty
Dim evImage As String = String.Empty
Dim capacity As Integer = 0
Dim soldseats As Integer = 0
Dim seatsleft As Integer = 0
Dim evdate As String = String.Empty
Dim evtimestart As String = String.Empty
Dim evtimeend As String = String.Empty
Dim EditLink As String = String.Empty
Dim DeletedLink As String = String.Empty
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
id = DataBinder.Eval(e.Item.DataItem, "oi_id")
evTitle = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "title"))
evImage = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "image"))
evdate = ComFunctions.ConvertToDate(DataBinder.Eval(e.Item.DataItem, "eventsdatestart"))
capacity = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "capacity"))
seatsleft = (capacity - soldseats)
evtimestart = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdatestart")))
evtimeend = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdateend")))
Dim obj_DATA_Capacity As New DATA_Events()
soldseats = obj_DATA_Capacity.GetSeatsSold(id)
e.Item.Cells(0).Text = id
e.Item.Cells(1).Text = evTitle & "<br />" & evdate & " " & evtimestart & " - " & evtimeend
e.Item.Cells(2).Text = "<img src=""" & AppSettings("Events_ImagePath") & "/Thumb/" & evImage & """ width=""100"" />"
e.Item.Cells(3).Text = "$" & ComFunctions.ConvertToDecimal(DataBinder.Eval(e.Item.DataItem, "oi_price"), 2)
lst = CType(e.Item.FindControl("lstQty"), ListBox)
If seatsleft > 0 Then
'lst.Items.Add(0)
For I = 1 To seatsleft
lst.Items.Add(I)
Next
End If
lst.ID = id
lst.SelectedValue = ComFunctions.ConvertToInt(DataBinder.Eval(e.Item.DataItem, "oi_qty"))
rbd = CType(e.Item.FindControl("DeleteThis"), ImageButton)
rbd.CommandArgument = id
End If
Catch ex As Exception
Errorlog(ex, "quickCart.cartList_ItemDataBound()")
End Try
End Sub
I'm not sure why it does not work the first time, by the way, what does "not work" actually mean? But apart from that, your way to get the text of the first cell in the current DataGridItem is odd.
This is much more directly:
Dim lb = DirectCast(sender, ListBox)
Dim item = DirectCast(lb.NamingContainer, DataGridItem)
Dim oiID = Int32.Parse(item.Cells(0).Text)
Maybe it helps also get it working.

Session disappears unexpectedly

The site is a buy/sell site and the page the code comes from is the "add product" page.
The problem is that the session("change") becomes nothing by some reason, I can't find any errors. The payment.aspx have a button that sends me back to the page with a session("change").
The reason I see the problem is that when I try to edit something the category gets restetted to the first in the list. and when I debug I see that the session is nothing, though it should be something
Heres the code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
If Not stats > 0 Then
If Session("change") IsNot Nothing Then
Dim dc As New DataClassesDataContext
Dim getP = From prod In dc.Products _
Where prod.ProductID = CInt(Session("change")) _
Select prod
If getP.Any Then
If rdbSell.Checked = True Then
getP.FirstOrDefault.BuySell = True
Else
getP.FirstOrDefault.BuySell = False
End If
If ddlSubSubcat.SelectedValue IsNot String.Empty Then
getP.FirstOrDefault.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
getP.FirstOrDefault.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
getP.FirstOrDefault.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
getP.FirstOrDefault.CountyID = CInt(ddlCounty.SelectedValue)
getP.FirstOrDefault.E_mail = txtEmail.Text
getP.FirstOrDefault.Date = DateTime.Now
getP.FirstOrDefault.Active = 0
getP.FirstOrDefault.Alias = txtAlias.Text.Replace("'", "''")
getP.FirstOrDefault.ShowEmail = 0
Dim PreID As Integer = getP.FirstOrDefault.ProductID
If chkShowEmail.Checked = True Then
getP.FirstOrDefault.ShowEmail = 1
Else
getP.FirstOrDefault.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
getP.FirstOrDefault.ShowPhone = 1
Else
getP.FirstOrDefault.ShowPhone = 0
End If
getP.FirstOrDefault.Headline = txtHeadline.Text
getP.FirstOrDefault.Password = txtPassword.Text
getP.FirstOrDefault.Phone = txtPhone.Text
getP.FirstOrDefault.Price = txtPrice.Text
If chkUnknown.Checked = True Then
getP.FirstOrDefault.YearModel = String.Empty
Else
getP.FirstOrDefault.YearModel = ddlYear.SelectedValue
End If
For Each item In libPictures.Items
Dim i As String = item.ToString
Dim imagecheck = From img In dc.Pictures _
Where img.Name = i And img.ProductID = CInt(Session("change")) _
Select img
If imagecheck.Any Then
Else
Dim img As New Picture
img.Name = item.ToString
img.ProductID = CInt(Session("change"))
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
End If
Next
dc.SubmitChanges()
Session.Remove("change")
Response.Redirect("~/precheck.aspx?id=" + PreID.ToString)
End If
Else
Dim dc As New DataClassesDataContext
Dim prod As New Product
If rdbSell.Checked = True Then
prod.BuySell = True
Else
prod.BuySell = False
End If
If ddlSubSubcat.DataValueField IsNot String.Empty Then
prod.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
prod.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
prod.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
prod.CountyID = CInt(ddlCounty.SelectedValue)
prod.E_mail = txtEmail.Text
prod.Date = DateTime.Now
prod.Active = 0
prod.Alias = txtAlias.Text.Replace("'", "''")
prod.ShowEmail = 0
If chkShowEmail.Checked = True Then
prod.ShowEmail = 1
Else
prod.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
prod.ShowPhone = 1
Else
prod.ShowPhone = 0
End If
prod.Headline = txtHeadline.Text
prod.Password = txtPassword.Text
prod.Phone = txtPhone.Text
prod.Price = txtPrice.Text
If chkUnknown.Checked = True Then
prod.YearModel = String.Empty
Else
prod.YearModel = ddlYear.SelectedValue
End If
dc.Products.InsertOnSubmit(prod)
dc.SubmitChanges()
Dim PreID As Integer = prod.ProductID
For Each item In libPictures.Items
Dim img As New Picture
img.Name = item.ToString
img.ProductID = prod.ProductID
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
Next
Session.Remove("change")
Response.Redirect("./precheck.aspx?id=" + PreID.ToString, False)
End If
End If
stats = 0
'Catch ex As Exception
'End Try
End Sub
It depends upon how the application is managing session state. If your session state is managed InProc then if the application pool is recycled then all your session information will be lost. If that is happening then it could be a good option to store session state in SQL Server which will persist between app pool recycling.
More info:
ASP.NET Session State Overview
ASP.NET State Management Recommendations

Resources