Page_Load not update after click the button - asp.net

I have a simple ASP.NET page:
sub Page_Load
//Get data form databse and show it
end sub
sud deletsome(Source As Object, e As EventArgs)
//delete one record when user click on submit button
end sub
When I click the button, the page reload, all the data have no change, I must re-enter the page again, the record I have delete disappear.
Can you show me why?
The full code here:
<%# Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="SELECT * FROM [user]"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
sub deletesome(Source As Object, e As EventArgs)
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="DELETE FROM [user]WHERE id = #ID"
dbcomm=New OleDbCommand(sql,dbconn)
dbcomm.Parameters.AddWithValue("ID", tb1.Text)
dbcomm.ExecuteNonQuery()
end sub
</script>
<html>
<body>
<form runat="server">
<asp:TextBox id="tb1" runat="server" />
<asp:Button id="b1" Text="Submit" runat="server" OnClick="deletesome" />
<asp:Repeater id="customers" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr bgcolor="#b0c4de">
<th>ID</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr bgcolor="#f0f0f0">
<td><%#Container.DataItem("id")%> </td>
<td><%#Container.DataItem("username")%> </td>
<td><%#Container.DataItem("userphone")%> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
<hr />
</body>
</html>

In asp page life cycle, page load happens before the button click (I know, it's kind of strange). The easiest work around is to place your code in the page "PreRender" event.

Use if(!IsPostBack) on page load.

You have not added the !IsPostBack condition in your page load event. When you click the button your page's load event is first called before the click event handler and it will reload the data again. That's the issue.
It should be like...
sub Page_Load
IF(!IsPostBack) ' This condition will be true when the page loads the first time
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="SELECT * FROM [user]"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
EndIf
end sub

try this
<%# Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
If Page.IsPostBack = False Then
LoadData()
end sub
sub deletesome(Source As Object, e As EventArgs)
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="DELETE FROM [user]WHERE id = #ID"
dbcomm=New OleDbCommand(sql,dbconn)
dbcomm.Parameters.AddWithValue("ID", tb1.Text)
dbcomm.ExecuteNonQuery()
LoadData()
end sub
sub LoadData
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="SELECT * FROM [user]"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>
<html>
<body>
<form runat="server">
<asp:TextBox id="tb1" runat="server" />
<asp:Button id="b1" Text="Submit" runat="server" OnClick="deletesome" />
<asp:Repeater id="customers" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr bgcolor="#b0c4de">
<th>ID</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr bgcolor="#f0f0f0">
<td><%#Container.DataItem("id")%> </td>
<td><%#Container.DataItem("username")%> </td>
<td><%#Container.DataItem("userphone")%> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
<hr />
</body>
</html>

Related

Dynamic page creation from db at run time in asp.net

I'm making E-Commerce website. Under that I want to show particular product details. From query string I can do that but that is not seo friendly so I need to make product name in url(from db) instead of using querystring. I tried following code but it is not working for me.
Error - The resource could not be Found
Global.asax
<%# Application Language="VB" %>
<%# Import Namespace="System.Web.Optimization" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
Sub Application_Start(sender As Object, e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
End Sub
Private Shared Sub RegisterRoutes(routes As RouteCollection)
routes.MapPageRoute("product-detail", "{product_name}.aspx", "product-detail.aspx")
End Sub
</script>
product-detail.aspx (Dynamic Page)
Private Sub product_detail_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim pageName As String = Me.Page.RouteData.Values("product_name").ToString()
End If
End Sub
shop.aspx (used listview control to display list of products)
<asp:ListView ID="products" runat="server" DataKeyNames="ID">
<ItemTemplate>
<asp:HyperLink ID="productID" runat="server" NavigateUrl='<%# Eval("product_name", "~/{0}") %>' CssClass="product-link">
<!--blocks-starts--><div class="blocks blocks-shop">
<asp:Image ID="readyStock" runat="server" ImageUrl="images/common/ready_stock_tag.png" Visible="false" CssClass="tag" />
<asp:Label ID="checkReadyStock" runat="server" Visible="false"></asp:Label>
<div class="block-img">
<img src='<%# Eval("image") %>' runat="server" id="proImg" />
</div>
<div class="block-content">
<span class="sku" style="font-size:0.6em !important">Item No. <asp:Label ID="skuID" runat="server" Text='<%# Eval("sku") %>'></asp:Label></span>
<h3>
<asp:Label ID="prodName" runat="server" Text='<%# Eval("product_name") %>'></asp:Label></h3>
<p><strong>
<asp:Label ID="priceRange" runat="server" Text='<%# Eval("price_range") %>'></asp:Label></strong></p>
</div>
</div><!--blocks-ends-->
</asp:HyperLink>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
</asp:ListView>
shop.aspx.vb
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "select * from products where status = 'active'"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
products.DataSource = dt
products.DataBind()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub

Pass Text From a List View Controller to a OnClick Sub VB.Net

Is there a way to pass text from a List View controller to a OnClick Subroutine? For example, there's a label in the List View and I've attached a Button in the List View and attached an OnClick Subroutine to it. Now I want to pass the text from the Label over to the OnClick Subroutine. I hope this make sense. Down below is my code:
VB.Net Code:
Protected Sub AmButtonClick(ByVal sender As Object, ByVal e As System.EventArgs)
Dim url As String = CType(Me.AmListViewDetails.FindControl("merchantLink"), Label).Text
Dim sb As New StringBuilder()
sb.Append("<script type = 'text/javascript'>"_
sb.Append("window.open('")
sb.Append(url)
sb.Append("');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), "script", sb.ToString())
End Sub
ASP.Net:
<asp:ListView runtat="server" ID="AmListViewDetails" ...>
<ItemTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<asp:Label ID="merchantLink" runat="server" Text='<%Eval("Link")%>' />
</td>
</tr>
<tr runat="server">
<td runat="server">
<asp:Button ID="AmBtn" runat="server" Text="Checkout" OnClick="AmButtonClick"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:ListView>
Add a CommandArgument property to the button. That's going to be the value passed to the event handler. You don't need an OnClick property.
<asp:Button ID="AmBtn" runat="server" Text="Checkout" CommandArgument="???" />
Your event handler would be
Sub AmListViewDetails_ItemCommand(object sender, ListViewCommandEventArgs e)
Dim valuePassedFromListView = Cstr(e.CommandArgument)
End Sub

When I selecting the combobox items its deleting or refreshing the attachments the file

I developed the compose message from email,
I attaching the files then i have selecting the combo box item its deleting the attachment files.
Here my ASP Code:
<asp:UpdatePanel ID="updatepanel" runat="server">
<ContentTemplate>
<tr>
<td valign="top">
<asp:Label ID="lblfile_name" runat="server" CssClass="labels">Upload File</asp:Label>
</td>
<td>
<div style="overflow-y: scroll; z-index: auto; height: 60px;">
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="multi" Visible="true" />
</div>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
<tr>
<td>
<telerik:RadComboBox EmptyMessage="----- Select -----" ID="cboTemplate" runat="server" Skin="WebBlue" AutoPostBack="true">
</telerik:RadComboBox>
</td>
</tr>
Here VB. NET CODE
Private Sub cboTemplate_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboTemplate.SelectedIndexChanged
If cboTemplate.SelectedValue = "--Select--" Then
lblErrMsg.Text = objcmnfunctions.GetErrMsg("B2B_WAR_110")
SetFocus(anc_err)
Exit Sub
End If
objdbconn.OpenConn()
msSQL = " Select mailtemplate_gid, template_name, template_content " & _
" from crm_trn_tmailtemplates " & _
" where mailtemplate_gid = '" & cboTemplate.SelectedValue & "'"
objOdbcDataReader = objdbconn.GetDataReader(msSQL)
If objOdbcDataReader.HasRows = True Then
objOdbcDataReader.Read()
radmailcontent.Content = objOdbcDataReader.Item("template_content").ToString
End If
objOdbcDataReader.Close()
objdbconn.CloseConn()
End Sub
Store the value of FileUpload1 to Session Object
If Session("FileUpload1") Is Nothing AndAlso FileUpload1.HasFile Then
Session("FileUpload1") = FileUpload1
ElseIf Session("FileUpload1") IsNot Nothing AndAlso (Not FileUpload1.HasFile) Then
FileUpload1 = DirectCast(Session("FileUpload1"), FileUpload)
ElseIf FileUpload1.HasFile Then
Session("FileUpload1") = FileUpload1
End If
The reason the dropdown is clearing the value from Upload is because it is set to AutoPostBack="true"

Accessing button in repeater control

I'm trying - quite unsuccessfully - to access a button inside a repeater control. I have a repeater set up on a page that displays movies that are currently showing in cinemas. I have created two buttons and added them to the repeater - one for trailer and another for review. For the review I want to link to another page which will have another repeater with paging enabled. When a users clicks the review button they should be brought to a page that shows only the reviews for that specific movie. This is that code I have:
MARKUP:
The repeater:
<asp:Repeater ID="movies" runat="server">
<ItemTemplate>
<table width="641px">
<tr>
<td>
<span style="font-weight:bold;font-size:16px;">
<%# Container.DataItem("MovieTitle")%>
</span>
</td>
<td>
<span style="float:right;">
<asp:Image ID="Image1" runat="server" ImageUrl = '<%# Eval("Total")%>' style="width:80px;height:14px;"/>
</span>
</td>
</tr>
<tr>
<td colspan="2">
<hr style="height:1px;border-bottom:none;color:#e3e3e3;"/>
</td>
</tr>
</table>
<table width="641px">
<tr>
<td>
<asp:Image ID="Image2" runat="server" ImageUrl = '<%# Eval("MovieImageFileName")%>' style="width:180px;height:108px;border:1px solid #e3e3e3;"/>
</td>
<td style="vertical-align:top;">
<%# Container.DataItem("Synopsis")%>
</td>
</tr>
</table>
<table width="641px">
<tr>
<td>
<span style="float:right">
<asp:Button ID="btnTrailer" runat="server" Text="Trailer" BackColor="#FF9900" ForeColor="White" />
<asp:Button ID="btnReview" runat="server" Text="Review" BackColor="#FF9900" ForeColor="White" CommandName="Review" />
</span>
</td>
</tr>
<tr>
<td>
<hr style="height:1px;border-bottom:none;color:#e3e3e3;"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
CodeBehind:
Dim movie_title As String
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim myConn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim dr, aDataReader As OleDbDataReader
Dim query, movieID As String
movie_title = Request.QueryString("id")
myConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
myConn.Open()
Dim sqlQuery = "Select movieID From Movies"
Dim aCmd = New OleDbCommand(sqlQuery, myConn)
aDataReader = aCmd.ExecuteReader()
If aDataReader.Read() = True Then
movieID = aDataReader(0)
Else
movieID = "0"
End If
query = ("Select MovieTitle, Genre, Synopsis, Starring, Total, Director, MovieImageFileName From Movies, MovieReviews, MReviewRatings WHERE Movies.MovieID = MovieReviews.MovieID AND MovieReviews.MReviewID = MReviewRatings.MReviewID AND ReviewerTypeID = 1")
cmd = New OleDbCommand(query, myConn)
dr = cmd.ExecuteReader()
movies.DataSource = dr
movies.DataBind()
End Sub
Protected Sub movies_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles movies.ItemCommand
If e.CommandName = "Review" Then
Response.Redirect("testingreviews.aspx?id = '" & movie_title)
End If
End Sub
When I run page the page displays but when I click the review button I get the following error:
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/>
in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or
callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.
RegisterForEventValidation method in order to register the postback or callback data for validation.
Anyone any ideas on what I am doing wrong? I am very new to asp.net.
If you want to access a button use the event ItemCreated or maybe its ItemDataBound.
Handles movies.ItemCreated
In that event you can then refeer to the button using FindControl,
Something like this
Sub Movies_ItemDataBound(Sender As Object, e As RepeaterItemEventArgs) Handles movies.ItemDataBound
Dim Btn As Button = CType(e.Item.FindControl("ButtonName"),Button)
End Sub

How do I transfer a value from one page to another in hidden parameters instead of a querystring?

What's wrong with this code?
Source page : Default.aspx
<form id="form1" action ="Default2.aspx" method="post" runat="server">
<table>
<tr>
<td>Merchant Id</td>
<td><asp:TextBox ID="SRCSITEID" Text="T521" runat="server"></asp:TextBox></td>
</tr>
</table>
<table>
<tr>
<td>
<asp:Button ID="Submit" runat="server" Text="Submit" /></td>
</tr>
</table>
</form>
Destination page : Default2.aspx
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
Default2.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
TextBox1.Text = Request("SRCSITEID").ToString()
Catch
End Try
End Sub
You could try
Page1
Session["someKey"] = ValueFromPage1;
and in Page2
var valueFromPage1 = Session["someKey"];
try
Request.Form("SRCSITEID")
because you use post method
Take a look at Cross Page Posting (MSDN Link)
It's like doing a postback only you post back to a completely different page.
Example Code:
If Not Page.PreviousPage Is Nothing Then
Dim SourceTextBox As TextBox
SourceTextBox = CType(PreviousPage.FindControl("SRCSITEID"), TextBox)
If Not SourceTextBox Is Nothing Then
TextBox1.Text = SourceTextBox.Text
End If
End If

Resources