VB.Net Handles button click event in code behind - asp.net

Having an issue with my button click event. I needed to add this button from one page to another so naturally it was copied and variables changed out within the click event method to match the new page. in the HTML side I added the button there too (stating in case someone wonders if I forgot that part).
Everything is identical to the other page... The issue is... when I try to run it to test the button I get a build error with no errors being displayed. One time I managed to get an error that stated "Handles clause requires a WithEvents variable defined in the containing type or one of its base types." So I commented out the handles portion of the method and it runs yay! except... the button doesn't work. I have tried a few suggestions that stated to restart the IDE, and where someone also mentioned to comment out the handles portion. Is there something I am missing?
<tr>
<td style="width: 209px" valign="middle" align="left"></td>
<td style="width: 7px;" valign="middle"></td>
<td valign="bottom" align="left">
<br>
<asp:Button ID="btnSaveAsExcel" runat="server" Width="264px" Text="Export to Excel"></asp:Button>
</td>
<td valign="middle" align="left"></td>
</tr>
Private Sub btnSaveAsExcel_Click(sender As Object, e As EventArgs) Handles btnSaveAsExcel.Click
If dgFacilitySummary.Visible Then
Dim DummydgFacilitySummary As New DataGrid
DummydgFacilitySummary.DataSource = Session("dsFacilitySummary").tables(0)
DummydgFacilitySummary.DataBind()
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & "Faci+lity Summary Report" & ".xls")
HttpContext.Current.Response.Charset = ""
EnableViewState = False
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
DummydgFacilitySummary.RenderControl(hw)
HttpContext.Current.Response.Write(sw.ToString())
HttpContext.Current.Response.End()
ElseIf dgFacilities.Visible Then
Dim DummydgFacilities As New DataGrid
DummydgFacilities.DataSource = Session("dsFacilityMatches").tables(0)
DummydgFacilities.DataBind()
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & "Facility Summary Report" & ".xls")
HttpContext.Current.Response.Charset = ""
EnableViewState = False
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
DummydgFacilities.RenderControl(hw)
HttpContext.Current.Response.Write(sw.ToString())
HttpContext.Current.Response.End()
End If
End Sub
both of that is exactly how it is on another page and it works there.

Try deleting the btnSaveAsExcel_Click() method from your code behind file. Then select btnSaveAsExcel in the drop down list on the upper left of the IDE just above your code. That will populate the drop down list on the upper right with all the events for the btnSaveAsExel button. Select the OnClick event and that will create a btnSaveAsExcel_Click() method.
It would probably be a good idea to only copy the markup and then use the method I just described to create the event handlers in the code behind file.

Related

How can I change File Info in Ajax File Upload Control ,Asp.net(VB)?

I am creating a drag file upload by using Ajax File Upload Control in Asp.net(VB).
I want to show file name, uploaded datetime, file size when I dragged into panel.
How can I do for that setting?
I could change the text for droparea like
$(document).ready(function () {
Sys.Extended.UI.Resources.AjaxFileUpload_Pending = "保留中";
Sys.Extended.UI.Resources.AjaxFileUpload_Remove = "削除";
Sys.Extended.UI.Resources.AjaxFileUpload_Uploaded = "アップロード済";
Sys.Extended.UI.Resources.AjaxFileUpload_Uploading = "アップロード中";
Sys.Extended.UI.Resources.AjaxFileUpload_UploadedPercentage = "アップロード中 {0} %";
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "アップロード";
document.getElementsByClassName
$(".ajax__fileupload_dropzone").text("ここにファイルをドロップ");
document.getElementsByClassName
$(".ajax__fileupload_uploadbutton").text("アップロード");
});
But I don't know how to change file info display.
This is my drag form and I want to change from application/pdf to uploaded datetime
You can't really display the "time" of up-load until the user starts.
You ALREADY can see the file size in your screen cap, so why the need for that?
you have:
so in above, you see the file name, you see the file size.
However, until such time you hit up-load and start up-loading files, you don't know yet the up-load time as of yet, do you?
So, when you hit up-load files, then each file selected will be up-loaded, and in the server side (code behind), you have this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now code to add say to a database table of files up-loaded.
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL = "INSERT INTO MyUpoadFiles (FileName, UpLoadTime, Size, User_id) " &
"VALUES (#File, #Time,#Size, #User)"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
With cmdSQL.Parameters
.Add("#File", SqlDbType.NVarChar).Value = e.FileName
.Add("#Time", SqlDbType.DateTime).Value = Date.Now
.Add("#Size", SqlDbType.Int).Value = e.FileSize
.Add("#User", SqlDbType.Int).Value = Membership.GetUser.ProviderUserKey
End With
cmdSQL.ExecuteNonQuery()
End Using
End Using
End Sub
Now, when ALL files are up-loaded, then the server side even UpLoadComplete all will fire, and THEN you can take the above list/table and display the files up-loaded along with the FileName, size, and time.
But, you really don't have the ability to display the file information such as what time until such time you uploaded the file and then have the time, right?
Edit:
Perhaps the idea above was not all that clear. What I am suggesting is that you have the up-loader on the page.
So, say we drop in this markup:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" />
<asp:Button ID="cmdDone" runat="server" Text="Done" CssClass="btn" ClientIDMode="Static"/>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table"></asp:GridView>
</div>
And note how we use the client side all done click.
So, we now have this:
We hit upload, and now we see this:
Now we should (need to) hide the Done button - we have the upload clicking on that done button for us.
So that button in theory should become this to hide it:
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
And the code for that button is this:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
Dim rstFiles As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "select FileName, UpLoadTime, Size, User_id from MyUpLoadFiles"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstFiles.Load(cmdSQL.ExecuteReader)
End Using
End Using
Gfiles.DataSource = rstFiles
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub

Setting Visible in PageLoad

I am running Visual Studio 2015 community, and I am experiencing some severe weirdness.
I have a page with a form the goes something like this:
<form>
<label...>
<textbox....>
<label...>
<textbox....>
....
<label...>
<textbox....>
<asp:Button ID="Sbutton1" runat="server" Text="Save Changes" CssClass="CSubmitRight" />
<asp:Button ID="Sbutton2" runat="server" Text="Go Back" CssClass="CSubmitRight" OnClientClick="JavaScript: history.go(-2); return false;" />
</form>
Now the problem is that when I try on page load or load complete to set the visibility of the buttons with a simple SButton1.visible = true and then try to run the page in debug mode, I get a message that there are build errors. When I comment out the visibility line, no problems running the code. I have no errors or warnings in the Error List.
I have tried restarting VS as that sometimes fixes annoying issues. I have tried putting them in Panels and setting the visibility of the panels, and I get the same error. I tried putting them in div's and then calling a JS function to change the display property of the div from On Page Load, but it doesn't change the visibility of the divs.
Why am I getting a compile error? Any clues?
May be you have syntax error. Asp controls have a property "Visible", so that should work. Check whether you have typo or matching case. In C# "visible" and "Visible" both are different.
SButton1.Visible = true;
or please post the exact error you are getting.
Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load
ButtonBlock1.Visible=true
ButtonBlock2.Visible=false
If IsPostBack then
UpdateBatch()
ButtonBlock1.Visible=false
ButtonBlock2.Visible=true
Else
Dim conn As SqlConnection = new SqlConnection(strConnString)
Dim da As SqlDataAdapter = new SqlDataAdapter()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "SQL SELECT CRAP"
da.SelectCommand = cmd
Dim ds As DataSet = new DataSet()
conn.Open()
da.Fill(ds)
selScanUser.DataSource = ds
selScanUser.DataValueField = "ID"
selScanUser.DataTextField = "UserName"
selScanUser.DataBind()
conn.Close()
cmd.Connection.Close()
cmd.Connection.Dispose()
End If
End Sub

How to remove a Gridview from an ASPX page?

I have an Aspx page that displays a GridView. The gridview would appear with data that was depending on which catergory was selected from a drop down menu. The user has the option to then download this as a CSV file (export to CSV). I now want the Gridview not to appear (beacuse it is so large it often just hangs) but instead to be able to download a CSV file with the data from the gridview. I have successfully built the button allowing for the download of this data by clicking the button. However, I now cannot open the page without the gridView appearing. I tried to comment out the Gridview code - this just broke the page. I tried to set the gridview as Visible="False" but this did not work either. What else can I do to prevent the gridview from appearing and the user to be taken straight to a download dialogue box?
wrap your Gridview to a div and set it to display:none in asp.net code –
Ex: <div id="divhidegrid" runat="server" style="display:none;" > <asp:GridView ID="gvtest" runat="server" > </div> like this
You can load your data in DataSet or DataTable from Code Behind and then export it directly to Excel/CSV without assigning it to GridView such as in the following example to export it to Excel:
Public Sub ExportToExcel(dt As DataTable)
If dt.Rows.Count > 0 Then
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.[End]()
End If
End Sub
If you get errors like control must be placed in inside of form tag you may also be required put the following code in your backend (Reference: export-data-to-excel-from-datatable-gridview-aspnet-csharp)
Public Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
C# Version of above code:
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0) {
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
public void VerifyRenderingInServerForm(Control control)
{
// Verifies that the control is rendered
}

Datagrid from Contentplace holder aspx page, Form is on Master page

This is asp.net application in VB. I have a master page and it has several contenet place holders have child pages. I have datagrid on those child or sub pages. I am trying to export these ASP:datagrids to excel. I know we have good examples of doing this. I am using following method:
Dim excelFileName As String = "Filename" + "_" + Date.Today + ".xlsx"
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" + excelFileName)
Dim stringWriter As New System.IO.StringWriter()
Dim textWriter As New HtmlTextWriter(stringWriter)
dgrid.RenderControl(textWriter)
Response.Write(stringWriter.ToString())
Response.End()
My problem is I am not able to do it because it says that for using this code the grid and button should be under tag with property runat=Server. My trials were.
Tried to add this grid to form using form.control.add(dGrid). It did not let me as I have <% %> code restriction. Which is requirement so I can not get rid of it.
Use Bind() method after datagrid is loaded, which ofcourse give me no values on excel.
Tried to use master page to findcontrol on run time from the loaded page. But still it says should be under tag with property runat=Server.
So Question Is : how to use the master page tag at the child (in Contentplaceholder)

ASP.NET Losing listbox binding on viewchange?

Ok so what seems like a basic problem is getting the better of me and my exstensive google efforts have come up short. Perhaps I don't understand enough to ask the right questions.
Here's my problem:
I have a formview control, or rather a series of them, each page displaying entry from previous forms, for a higher level access to approve/edit as needed. So, on form "B", I have the contents of form "A" and the blank part of "B" to filled out...So two seperate fromviews on the page.."A" and "B"
That works fine, the issue is when I change the mode to edit previous entry. So if I have a button or the default linkbutton to change from ReadOnly to Edit I not only lose bindings but any efforts to counteract that have left me with issues when I postback.
DUE TO LENGTH I'M LEAVING SOME CODE OUT
On my button I'm using FormView2.ChangeMode(FormViewMode.Edit) to change view, the default link button I've not changed
Bindings on my listboxes are setup like:
If Not Page.IsPostBack Then
'pulling bindings from table
cmd = New OleDbCommand("SELECT * FROM mslToi", objCon)
objReader = cmd.ExecuteReader
lst1.DataValueField = "listing"
lst1.DataTextField = "listing"
lst1.DataSource = objReader
lst1.DataBind()
'pre-selecting input data from form "A"
cmd = New OleDbCommand("SELECT [type_of_injury] FROM S2childToi WHERE ID = " & qs & "", objCon)
objReader = cmd.ExecuteReader
Do While objReader.Read
For Each y As ListItem In lst1.Items
If y.Text = objReader.Item(0) Then
y.Selected = True
End If
Next
Loop
end if
In the page load event.
MARKUP FOR THE FORMVIEW AS ASKED
<asp:FormView ID="FormView2" runat="server"
Width="100%" DataSourceID="AccessDataSource4">
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:FormView>
'''that is the short and sweet of the formview markup as requested. It may also be worth noting that it doesn't matter what mode I start in, if I change modes it equals same result'''
That works fine so far...it's when I change view to Edit that my listbox appears to no longer be bound (controls appear but have no content). My thought is that obviously I'm blocking out my code from postback events (I have a reason for this). I can use this code (without the If Not Page.IsPostBack) to force the selections and bindings but whenever I postback they will defualt to the table data, which can't happen, each listbox needs to postback so I can check for a certain selection. So what happens is the user input is trumped. Short and sweet.
I'm sorry that I can't explain better, any advice is much appreciated. If I can asnwer any questions or post code let me know.
Try this:
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
<asp:ListBox ID="ListBoxReadonly" runat="server"></asp:ListBox>
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="ListBoxEdit" runat="server"></asp:ListBox>
</EditItemTemplate>
</asp:FormView>
Then, in your FormView's databound event, bind the data into your listbox depending on the current view.
Protected Sub FormView1_DataBound(sender As Object, e As EventArgs) Handles FormView1.DataBound
Dim myListBox As ListBox
If FormView1.CurrentMode = FormViewMode.ReadOnly Then
myListBox = DirectCast(FormView1.FindControl("ListBoxReadonly"), ListBox)
ElseIf FormView1.CurrentMode = FormViewMode.Edit Then
myListBox = DirectCast(FormView1.FindControl("ListBoxEdit"), ListBox)
End If
If myListBox IsNot Nothing Then
myListBox.DataValueField = "listing"
myListBox.DataTextField = "listing"
myListBox.DataSource = GetListingData()
myListBox.DataBind()
' your pre-select code here...
End If
End Sub

Resources