OnClientClick does not work with asp.net and vb.net - asp.net

I try to create a dynamic web solution with ASP.NET and VB.
My webpage looks like this:
<div id="menu" style="position:relative;text-align:center">
<asp:PlaceHolder runat="server" id="PHimg1" />
<asp:PlaceHolder runat="server" id="PHimg2" />
<asp:PlaceHolder runat="server" id="PHimg3" />
<br />
<asp:PlaceHolder runat="server" id="PHimg4" />
<asp:PlaceHolder runat="server" id="PHimg5" />
<asp:PlaceHolder runat="server" id="PHimg6" />
<br />
<asp:PlaceHolder runat="server" id="PHimg7" />
<asp:PlaceHolder runat="server" id="PHimg8" />
<asp:PlaceHolder runat="server" id="PHimg9" />
</div>
The VB part like this:
Public Class index
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Load_Main()
End Sub
Protected Sub Load_Main()
Dim img1 As New ImageButton()
Dim img2 As New ImageButton()
Dim img3 As New ImageButton()
Dim img4 As New ImageButton()
Dim img5 As New ImageButton()
Dim img6 As New ImageButton()
img1.ImageUrl = "./resources/EssenTrinken.png"
img1.OnClientClick = "Load_Eating()"
img2.ImageUrl = "./resources/Einkaufen2-black.png"
img3.ImageUrl = "./resources/Special-black.png"
img4.ImageUrl = "./resources/KosmetikWellness.png"
img5.ImageUrl = "./resources/KulturGeschichte.png"
img6.ImageUrl = "./resources/Unterhaltung2-black.png"
PHimg1.Controls.Add(img1)
PHimg2.Controls.Add(img2)
PHimg4.Controls.Add(img3)
PHimg5.Controls.Add(img4)
PHimg7.Controls.Add(img5)
PHimg8.Controls.Add(img6)
End Sub
Protected Sub Load_Eating()
Dim img1 As New ImageButton()
Dim img2 As New ImageButton()
Dim img3 As New ImageButton()
Dim img4 As New ImageButton()
Dim img5 As New ImageButton()
Dim img6 As New ImageButton()
img1.ImageUrl = "./resources/zurueck.png"
img2.ImageUrl = "./resources/Bars2.png"
img3.ImageUrl = "./resources/Cafe.png"
img4.ImageUrl = "./resources/FastFood2.png"
img5.ImageUrl = "./resources/Restaurant.png"
img6.ImageUrl = "./resources/Baeckerei.png"
PHimg1.Controls.Add(img1)
PHimg2.Controls.Add(img2)
PHimg3.Controls.Add(img3)
PHimg4.Controls.Add(img4)
PHimg5.Controls.Add(img5)
PHimg6.Controls.Add(img6)
End Sub
End Class
I want that if I click on one of the imagebutton the hole appereance of the frontpage dynamicly changes without loading the hole page new. So I defined several PlacHolder for that.
If I run the webapp but the functionality is not working if I hit the button.
I checked the source and found this tag:
<input type="image" name="ctl03" src="./resources/EssenTrinken.png" onclick="Load_Eating();" />
What is wrong with this solution?

If you are trying to do this from the code behind, then you need to add the Click event handler:
Protected Sub Load_Main()
Dim img1 As New ImageButton()
AddHandler img1.Click, AddressOf Img1Click
'rest of your code
and then have some function that does what you want:
Private Sub Img1Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
'some code
End Sub
Note, this will cause a postback. It is confusing on how you expect to dynamically change the front page without reloading the page and without using JavaScript...

Add to your Page_load a check for IsPostBack
if Not IsPostBack Then
Load_main()
End If
This will prevent your page_load method to recreate every button and resetting the value for the Image_click event

Related

Edit Gridview update issue

I have got a gridview which when you press select on a row it transfers you to another gridview page,
which displays more columns from that table to give more detail about that row.
I know how to do this using:
<asp:HyperLinkField DataNavigateUrlFields="MISAppID" DataNavigateUrlFormatString="ApplicationsDetails.aspx?MISAppID={0}" Text="Select" />
In the 1st Gridview then using a Stored-procedure on the second page it displays the correct row using the ID field.
In my current site on the second page, I have added an edit button that does edit the row correctly in my database but on completion, it breaks the site and I can't work out how to get it to just refresh the gridview
This is the error I get:
Exception Details: System.NotSupportedException: Updating is not
supported by data source 'SqlDataSource1' unless UpdateCommand is
specified.
Is it the case that my BindGrid is missing something or is the way I am using my Stored-procedure?
Here is my VB code:
Public Sub BindGrid() Handles SqlDataSource1.Selecting
End Sub
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
Dim misappId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
Dim application As String = TryCast(row.Cells(2).Controls(0), TextBox).Text
Dim url As String = TryCast(row.Cells(3).Controls(0), TextBox).Text
Dim access_group As String = TryCast(row.Cells(4).Controls(0), TextBox).Text
Dim creator_ein As String = TryCast(row.Cells(5).Controls(0), TextBox).Text
Dim data_location As String = TryCast(row.Cells(6).Controls(0), TextBox).Text
Dim purpose As String = TryCast(row.Cells(7).Controls(0), TextBox).Text
Dim active As String = TryCast(row.Cells(8).Controls(0), TextBox).Text
Dim business_owner As String = TryCast(row.Cells(9).Controls(0), TextBox).Text
Dim area As String = TryCast(row.Cells(10).Controls(0), TextBox).Text
Dim constr As String = ConfigurationManager.ConnectionStrings("myLocalConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("UPDATE tbl_AutomationCompassApplications SET Application = #Application, URL = #URL, Access_Group = #Access_Group, Creator_EIN = #Creator_EIN, Data_location = #Data_location, Purpose = #Purpose, Active = #Active, Business_Owner = #Business_Owner, Area = #Area WHERE MISAppID = #MISAppID")
cmd.Parameters.AddWithValue("#MISAppID", misappId)
cmd.Parameters.AddWithValue("#Application", application)
cmd.Parameters.AddWithValue("#URL", url)
cmd.Parameters.AddWithValue("#Access_Group", access_group)
cmd.Parameters.AddWithValue("#Creator_EIN", creator_ein)
cmd.Parameters.AddWithValue("#Data_location", data_location)
cmd.Parameters.AddWithValue("#Purpose", purpose)
cmd.Parameters.AddWithValue("#Active", active)
cmd.Parameters.AddWithValue("#Business_Owner", business_owner)
cmd.Parameters.AddWithValue("#Area", area)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
Ok, say we have a list of hotels - we want to display them, and then click on a row to eit.
(and you writing WAY too much code here).
So, lets say we drop in a gridview. Use the connection wizard - let it generate the markup.
THEN REMOVE the data source on the page, remove the datasource property of the gridview.
So, in less time then it takes me to write above? We have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="Edit"
PK = '<%# Container.DataItemIndex %>' OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
Note the cool trick I used to get the PK row index.
When you are looking at the grid, you can't double click on the button to wire up a event (code behind), but you CAN DO THIS!!!!
Note VERY care full in above - I typed in OnClick "=", when you HIT "=", then NOTE the inteli-sense that popped up - the create NEW event is what we need. Click on create new event - NOTHING seems to happen, but if we NOW go to code behind, we have a code stub for the button!!!
And note how I needed/wanted the PK row value - so I just shoved in and created my OWN custom attribute for that button. ("PK").
Ok, so our code to load up the grid is now this - and I included the button click code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Dim strSQL As String
strSQL = "SELECT * from tblHotels Order by HotelName"
Using cmdSQL As New SqlCommand(strSQL, New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Dim MyTable As New DataTable
MyTable.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = MyTable
GridView1.DataBind()
Session("MyTable") = MyTable
End Using
End Sub
Protected Sub cmdView_Click(sender As Object, e As EventArgs)
Dim MyBtn As Button = sender
Session("RowID") = MyBtn.Attributes.Item("PK")
Response.Redirect("~/EditHotel.aspx")
End Sub
Look how clean and simple the above is!!! I find this as easy say as MS-Access coding!!!
Ok, so the grid now looks like this:
Note the button click code.
So, our markup is this for the new page (to edit hte ONE row).
<div style="float:left;width:20%">
<div style="text-align:right">
First Name :<asp:TextBox ID="txtFirstname" runat="server" Width="150"></asp:TextBox> <br />
Last Name :<asp:TextBox ID="txtLastname" runat="server" Width="150"></asp:TextBox> <br />
Hotel Name :<asp:TextBox ID="txtHotel" runat="server" Width="150"></asp:TextBox> <br />
City :<asp:TextBox ID="txtCity" runat="server" Width="150"></asp:TextBox> <br />
Active :<asp:CheckBox ID="Active" runat="server" Width="150"></asp:CheckBox>
</div>
</div>
<div style="clear:both">
<br />
<asp:Button ID="cmdSave" runat="server" Text ="Save " />
<asp:Button ID="cmdCancel" runat="server" Text="Cancel" Style="margin-left:20px" />
</div>
</form>
and it looks like this:
and the load code and save button code for this page?
This:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadInfo()
End If
End Sub
Sub LoadInfo()
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
txtFirstname.Text = MyRow("FirstName")
txtLastname.Text = MyRow("LastName")
txtCity.Text = MyRow("City")
txtHotel.Text = MyRow("HotelName")
Active.Checked = MyRow("Active")
End Sub
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
MyRow("FirstName") = txtFirstname.Text
MyRow("LastName") = txtLastname.Text
MyRow("City") = txtCity.Text
MyRow("HotelName") = txtHotel.Text
MyRow("Active") = Active.Checked
Using cmdSQL As New SqlCommand("SELECT * from tblHotels where ID = 0",
New SqlConnection(My.Settings.TEST3))
Dim da As New SqlDataAdapter(cmdSQL)
Dim cmdUpdate As New SqlCommandBuilder(da)
da.Update(MyTable)
End Using
Response.Redirect("~/MyTours.aspx")
End Sub
Again, look how easy, clean and readable the code is.
Study the above example - you see that you don't need all that parameters code, and you see how little code is in fact required to select a row - jump to page to edit, and then you hit save - update the data and jump back to the grid row page.

GridView not populating on Page_Load but on PostBack or Refresh

In an ASP.NET WebForms application there are just two controls in an aspx page, a DropDownList and a GridView. There is no default selected value of DropDownList on Page_Load. Changing the selection in DropDownList populates GridView accurately.
When the page is requested with a URL parameter such as .../View_Details.aspx?C_ID=123, the selected value in DropDownList changes but GridView does not populate for the first time but refreshing the page shows the records for given URL parameter.
ASPX markup:
<%# Page Title="Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/HomePage.Master" CodeBehind="View_Details.aspx.vb" Inherits="App1.View_Details" %>
<asp:Content ID="Content4" ContentPlaceHolderID="BodyCP" runat="server">
<asp:DropDownList ID="CIDCombo" runat="server" DataSourceID="SqlDSCID" DataTextField="CName" DataValueField="CID" AutoPostBack="true"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDSCID" runat="server" ... ></asp:SqlDataSource>
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Fld1" />
<asp:BoundField DataField="Fld2" />
...
</Columns>
</asp:GridView>
</asp:Content>
Code Behind:
Private C_ID As Long
Dim con As SqlConnection = New SqlConnection(ConfigurationManager.Connect...)
Dim cmd As New SqlCommand()
Dim stSqlQry As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
C_ID = CLng(Request.QueryString("C_ID"))
If IsPostBack Then
Else
If C_ID > 0 Then
CIDCombo.SelectedValue = C_ID.ToString
LoadGVData(C_ID)
End If
End If
End Sub
Private Sub CIDCombo_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles CIDCombo.SelectedIndexChanged
If CIDCombo.SelectedIndex >= 0 AndAlso CLng(CIDCombo.SelectedValue) > 0 Then
LoadGVData(CLng(CIDCombo.SelectedValue))
End If
End Sub
Private Sub LoadGVData(ByVal lnCID As Long)
Try
If con.State <> ConnectionState.Open Then con.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter()
stSqlQry = "SELECT Fld1, Fld2 ... WHERE CID = #CID"
da = New SqlDataAdapter()
cmd = New SqlCommand(stSqlQry, con)
cmd.Parameters.AddWithValue("#CID", lnCID)
Dim dtDataTableInc As DataTable = New DataTable("t_Data")
da.SelectCommand = cmd
da.Fill(dtDataTableInc)
'SOME DATA MANIPULATION WITH DATATABLE'
'****************************************************************************'
'DEBUG MODE SHOWS DataTable HAS ROWS BUT DON'T SHOW UP FIRST TIME IN GRIDVIEW'
'****************************************************************************'
gvData.DataSource = dtDataTableInc
gvData.DataBind()
Catch ex As Exception
'EXCEPTION HANDLING
Finally
If con.State <> ConnectionState.Closed Then con.Close()
End Try
End Sub
I see you have AutoEventWireup="false" put it on true.
Just a general note:
When working with DropDownLists and using AutoPostBack=True
make use of an UpdatePanel since the User gets frustrated when he always see a white page flickering :)
if you use an UpdatePanel you use the Onload event to populate your data
and put UpdateMode=Conditional
Good luck and happy coding.

Dynamically generated Linkbutton does not fire Onclick event VB.Net

I have followed some of the instructions to create a new LinkButton at runtime with an event trigger and add an event handler for the LinkButton generated. I have no idea why the new LinkButton does not trigger the event added to it. Anyone please guide/correct me.
This is what I have right now.
ASPX:
<form id="myForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table class="mel-table" style="text-align: center" runat="server" id="mytab1">
<tbody>
<tr>
<td>Case Number :</td>
<td>
<asp:TextBox ID="caseNumber" runat="server"></asp:TextBox>
</td>
</tr>
</tbody>
</table>
<asp:Button OnClick="btnOK1_Click" ID="btnOK1" runat="server" Text="Save" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
ASPX.VB:
Protected Overloads Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("tablecontent") IsNot Nothing Then
mytab1 = CType(Session("tablecontent"), HtmlTable)
End If
End Sub
Public Function checking() As Boolean
Dim caseNo As Double
Try
caseNo = Convert.ToDouble((caseNumber.Text).Trim())
Catch ex As Exception
caseNo = 0
End Try
Dim r As New HtmlTableRow
Dim c0 As New HtmlTableCell
r.Cells.Add(c0)
Dim but As New LinkButton
but.ID = caseNo
but.Text = caseNo.ToString()
AddHandler but.Click, AddressOf LinkButton1_Click
c0.Controls.Add(but)
mytab1.Rows.Add(r)
Session("tablecontent") = mytab1
Return True
End Function
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)
'My Code here
End Sub
Protected Sub btnOK1_Click(sender As Object, e As EventArgs)
If (checking()) Then
ScriptManager.RegisterStartupScript(Page, Page.GetType, "Alert", "<script type='text/javascript'>alert('Success');</script>", False)
End If
End Sub
When you click on the "Save" button, save the data in either local storage or database and try to load the page again to fill the page with the content from the storage. In this case, you can have the content on the page and so, you can utilize the events also.
Whenever you create dynamic control you have to reload it on postback. I am using method call ReloadRows() for reloading added case which i am saving in ViewState:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Table class="mel-table" style="text-align: center" runat="server" id="mytab1">
<asp:TableRow>
<asp:TableCell>Case Number :</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="caseNumber" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Button OnClick="btnOK1_Click" ID="btnOK1" runat="server" Text="Save" />
</ContentTemplate>
</asp:UpdatePanel>
--------------------------------------------------------------------------------------------------------
Public Partial Class _Default
Inherits System.Web.UI.Page
Private listCaseNo As List(Of Double) = Nothing
Protected Sub Page_Init(sender As Object, e As EventArgs)
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs)
If ViewState("ListCases") IsNot Nothing Then
listCaseNo = DirectCast(ViewState("ListCases"), List(Of Double))
Else
listCaseNo = New List(Of Double)()
End If
ReloadRows()
End Sub
Public Function checking() As Boolean
Dim caseNo As Double = 0
Try
caseNo = Convert.ToDouble((caseNumber.Text).Trim())
Catch ex As Exception
caseNo = 0
End Try
Dim r As New TableRow()
Dim c0 As New TableCell()
r.Cells.Add(c0)
Dim but As New LinkButton()
but.ID = Convert.ToString(caseNo)
but.Text = caseNo.ToString()
AddHandler but.Click, AddressOf LinkButton1_Click
c0.Controls.Add(but)
mytab1.Rows.Add(r)
listCaseNo.Add(caseNo)
ViewState("ListCases") = listCaseNo
Return True
End Function
Private Sub ReloadRows()
For Each objCase As var In listCaseNo
Dim r As New TableRow()
Dim c0 As New TableCell()
r.Cells.Add(c0)
Dim but As New LinkButton()
but.ID = Convert.ToString(objCase)
but.Text = objCase.ToString()
AddHandler but.Click, AddressOf LinkButton1_Click
c0.Controls.Add(but)
mytab1.Rows.Add(r)
Next
End Sub
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)
'My Code here
End Sub
Protected Sub btnOK1_Click(sender As Object, e As EventArgs)
If (checking()) Then
End If
End Sub
End Class

Dynamically created buttons not calling function on postback

In my visual basic web application I have a list of generated buttons that are supposed to allow the download of a file on click.
I had the example working with generated buttons on pageload, but all of a sudden the download function stopped getting called on post back, and now all the button click does (for any of the buttons) is cause a page post back.
My code:
Public folder As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
folder = "Main"
PopulateFiles(folder)
End If
End Sub
Protected Sub PopulateFiles(ByVal folder As String)
Dim myConnection As SqlConnection
Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim myCommand As SqlCommand
Dim myDataReader As SqlDataReader
Dim text As String
Dim size As Decimal
Dim name As String
Dim type As String
Dim id As Integer
folderName.Text = folder
container.Controls.Clear()
myConnection = New SqlConnection(conString)
myConnection.Open()
myCommand = New SqlCommand("Uploads_GetAllFiles", myConnection)
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#folder", folder)
Try
myDataReader = myCommand.ExecuteReader()
If myDataReader.HasRows Then
Do While myDataReader.Read()
name = myDataReader.Item("Name")
type = myDataReader.Item("Type")
id = myDataReader.Item("File_ID")
size = Math.Round(myDataReader.Item("Size") / 1000, 2)
container.Controls.Add(New LiteralControl("<div class='newRow'>"))
text = "<div class='fileName'>" & name & "</div>"
container.Controls.Add(New LiteralControl(text))
text = "<div class='fileType'>" & type & "</div>"
container.Controls.Add(New LiteralControl(text))
text = "<div class='fileSize'>" & size.ToString() & "kb</div>"
container.Controls.Add(New LiteralControl(text))
container.Controls.Add(New LiteralControl("<div class='fileDownload'>"))
Dim newBtn As New Button
newBtn.ID = "link" & id
newBtn.Text = "Download"
newBtn.CssClass = "newbie"
AddHandler newBtn.Click, AddressOf Retreive_Doc
newBtn.CommandArgument = id
container.Controls.Add(newBtn)
container.Controls.Add(New LiteralControl("</div>"))
container.Controls.Add(New LiteralControl("<div class='fileDelete'>"))
Dim newDelBtn As New Button
newDelBtn.ID = "delete" & id
newDelBtn.Text = "Delete"
newDelBtn.CssClass = "delBtn"
AddHandler newDelBtn.Click, AddressOf Retreive_Xls
newDelBtn.CommandArgument = id
container.Controls.Add(newDelBtn)
container.Controls.Add(New LiteralControl("</div>"))
container.Controls.Add(New LiteralControl("</div>"))
Loop
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
myConnection.Close()
End Try
End Sub
Protected Sub Retreive_Doc(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Dim button As Button = sender
Dim id As Integer = button.CommandArgument
Dim cmd As SqlCommand = New SqlCommand("Uploads_GetFile")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", id)
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Sub
I could show the functions called from this function, but the initial function isn't even being called so I'm not sure there is a point.
My HTML is as follows:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="upload1" runat="server" /><asp:Button ID="test1" runat="server" Text="Upload" />
<asp:TextBox ID="folderTag" runat="server" ></asp:TextBox>
<asp:Button ID="search" runat="server" Text="Search" />
<asp:Label ID="folderName" runat="server">General</asp:Label><br />
<div id="navContainer" runat="server">
</div>
<div id="hiddenContent">
<asp:LinkButton ID="LinkButton1" CssClass="hide" runat="server" OnClick = "Retreive_Doc">Download Doc</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" CssClass="hide" runat="server" OnClick = "Retreive_Xls">Download xls</asp:LinkButton>
</div>
<div id="container" runat="server">
</div>
</form>
As I said before. This was working a few days ago and through the course of adding some other functionality somehow I lost it.
I'm unsure of why it posts back without calling any function.
Thanks for any help!
You need to recreate the controls with same ID in post back if you created them dynamically. Otherwise, they will disappear after postback.
Remove If Not IsPostBack Then in page load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
folder = "Main"
PopulateFiles(folder)
End Sub
Another thought:
Is there a reason not to use CommandEvent instead of Click event if you want CommandArgument?
Again, Is there a reason not to use PlaceHolder instead of <div id="container" runat="server">?
AddHandler newBtn.Command, AddressOf Retreive_Doc
newBtn.CommandArgument = id
....
protected void Retreive_Doc(object sender, CommandEventArgs e)

ASP.Net GridView doesn't refresh

I am relativity new to asp.net programming, so this one has me stumped. I manually created a dataset and set its value to the Datasource of the GridView control and then call the Databind method, but it isn't refreshing. I recreated a simple version of what I am doing so someone can advise me what I am doing wrong. I didn't include the Master file, as I didn't see it as pertainent.
Code for ASP page
<%# Page Language="vb" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestGridView._Default" %>
Updating price please stand by.
<p>
<asp:GridView ID="GV1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="VendorNumber" HeaderText="Vendor" />
<asp:BoundField DataField="PartNumber" HeaderText="Part or Sku" />
<asp:BoundField DataField="Message" HeaderText="Error Message" />
</Columns>
</asp:GridView>
</p>
<br />
<br />
<%
If Not Page.IsPostBack Then
Response.Write(Me.UpdatePricing())
End If
%>
Code for Code Behind
Public Class _Default
Inherits System.Web.UI.Page
Public Function UpdatePricing() As String
Dim showerrors As Boolean = False
Dim Head As New PnAHead()
Dim ds As DataSet = Head.GetErrorDataset()
If (ds.Tables("Errors").Rows.Count > 0) Then
showerrors = True
End If
If showerrors Then
GV1.DataSource = ds
GV1.DataBind()
End If
Return "Sales Line Number has been updated."
End Function
End Class
Class that creates the Dataset
Public Class PnAHead
Public Function GetErrorDataset() As DataSet
Dim dstemp = New DataSet()
Dim tbl As DataTable = dstemp.Tables.Add("Errors")
Dim col As DataColumn = tbl.Columns.Add("VendorNumber", System.Type.GetType("System.String"))
col.MaxLength = 20
col = tbl.Columns.Add("PartNumber", System.Type.GetType("System.String"))
col.MaxLength = 50
col = tbl.Columns.Add("Message", System.Type.GetType("System.String"))
col.MaxLength = 500
Dim row As DataRow
row = tbl.NewRow()
row("VendorNumber") = "Vendor 1"
row("PartNumber") = "Part Number 1"
row("Message") = "Message for Part 1"
tbl.Rows.Add(row)
row = tbl.NewRow()
row("VendorNumber") = "Vendor 2"
row("PartNumber") = "Part Number 2"
row("Message") = "Message for Part 2"
tbl.Rows.Add(row)
Return dstemp
End Function
End Class
You need to add your call to update pricing into the Page_Load event. You can also remove the Response.Write().
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Me.UpdatePricing()
End If
End Sub
You can do this in the .aspx page by wrapping the Page_Load event in script tags, like this:
<script type="text/VB" runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Me.UpdatePricing()
End If
End Sub
</script>
Or you can just add the Page_Load event to your code behind, which i think is preferable as you already have a code behind page.
Why don't you debug your code and check of the dataset has data or not,u can do this by adding a break point on the row where you set the data source,you can get into the properties of the dataset..and you will find a magnifier icon..click it,,a pop up window will open showing the set of data retrieved.

Resources