Setting Visible in PageLoad - asp.net

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

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

VB.NET Connection string ADODB Connection (Web.Config)

I write the code below to connect database using web config but cannot connect database using ADODB to fetch data from database into textboxes
Webconfig
<connectionStrings>
<clear />
<add name="constr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CustomerInfor.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>
SearchButton
Dim consString As String = System.Configuration.ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim objConn As New OleDbConnection(consString)
objConn.Open()
Please help with right code to fetch data from database into textboxes
Thanks
Ok, lets try this a bit different.
First up: Lets get the connection string OUT side of the code.
Like for desktop, or anything else? You can add values like connection string to the project like this:
And really nice is you get to use the connection builder to do this.
The above setting are shoved into web.config for you automatic.
So, setup your connection in above.
Ok, now in this case, I just shove on the screen a few text boxes for a user and hotel name.
Real plane jane like this:
<div style="width:25%;text-align:right;padding:25px;border:solid;border-width:1px">
<style> .tbox {width:260px;margin-left:5px;margin-bottom:15px;border-radius:8px;border-width:1px}</style>
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" class="tbox"/>
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" class="tbox" />
<br />
Last Name:<asp:TextBox ID="txtLast" runat="server" class="tbox"/>
<br />
City: <asp:TextBox ID="txtCity" runat="server" class="tbox"/>
<br />
Active:<asp:CheckBox ID="ckActive" runat="server" />
<br />
<br />
Ok, now our code to load this. I don't have a text box or source for the id, but a integer value OR a text value will work.
So, our code to load up is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Dim cmdSQL As OleDbCommand = New OleDbCommand()
cmdSQL.CommandText = "SELECT * from tblhotels where ID = #ID"
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = 23
Dim rst As DataTable = MyRst(cmdSQL)
With rst.Rows(0)
txtHotelName.Text = .Item("HotelName")
txtFirst.Text = .Item("FirstName")
txtLast.Text = .Item("LastName")
txtCity.Text = .Item("City")
ckActive.Checked = .Item("Active")
End With
ViewState("rst") = rst
End Sub
Note the cute helper routine MyRst.
So, you can use that routine EVERY where. eg:
Dim cmdSQL As OleDbCommand = New OleDbCommand("select * from RoomTypes")
Dim rst as DataTable = MyRst(cmdSQL)
So, it just a handy dandy routine. (you do NOT have to use parameters if you don't need them).
Ok, so we loaded the one row into the table (and we save that row for later use into ViewState)
Ok, so now we see this:
Now, the save code. Note how we used a record set (datatable) in place of a GAZILLION parameters.
We do this for quite a few reasons.
Strong data type conversion occurs here.
Parameter order for the save does not matter. I can cut-paste, or add 5 or 15 more columns here, and it works - and order does not matter!!!
So, now the save code.
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
SaveData()
End Sub
Sub SaveData()
Dim rst As DataTable = ViewState("rst")
Using con As New OleDbConnection(My.Settings.AccessTest2)
Using cmdSQL As New OleDbCommand("SELECT * from tblHotels WHERE ID = 0", con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmdSQL)
Dim daSQLU As OleDbCommandBuilder = New OleDbCommandBuilder(da)
con.Open()
With rst.Rows(0)
.Item("HotelName") = txtHotelName.Text
.Item("FirstName") = txtFirst.Text
.Item("LastName") = txtLast.Text
.Item("City") = txtCity.Text
.Item("Active") = ckActive.Checked
End With
da.Update(rst)
End Using
End Using
End Sub
NOTE: not a bug, I MOST certainly did use where ID = 0
So, the nice part is we can add more text box etc. We will have to add code to setup the text boxes, but at least the order don't matter.
Last but not least?
That helper routine, the one I use to fill datatables. I even use it for say filling out combo box (dropdown lists), or whatever.
Public Function MyRst(cmdSQL As OleDbCommand) As DataTable
Dim rstData As New DataTable
Using MyCon As New OleDbConnection(My.Settings.AccessTest2)
cmdSQL.Connection = MyCon
MyCon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
Return rstData
End Function
So note how we used the connection string setting that we setup in the project.
And since access is sensitive to parameter order, then I adopted the above idea of using a data table. Note that this approach also works for a grid, or even adding rows. When you run that update routine? rows added, rows edits, row deleted?
They all are done for you with the ONE da.Upate(rst).
Note also, you should set your project to run as x86, and not x64, since JET ONLY can work as x32. However, the ACE data engine can be had for x64 bits.

setting debug="false" in web.config

i am having this problem if i set debug=false in web.config file.
i had a treeview where all the nodes are loaded dynamically from code pagehide during Page_Load event
if i set debug="true" this works fine if i add another node form a button and so on.
But if i set it to false. nodes are loaded correctly during If Not IsPostBack Then if i add a new node, it will show correctly but if there is another postback,the newly added button will be disappeared and data are loaded from the first postback and i have to close the web and reopen again to load the new nodes to load.
the data will always remains at the first postback if i set debug to false.
anyone know why i am not getting new data from subsequent postback instead of first postback if i set debug to false?
please take note that i only having this issue on internet explorer 11. chrome and firefox i does not have this issue .
below is my code
If Not IsPostBack Then
Try
masternode = New TreeNod
masternode.Text = "Scale Management"
masternode.Value = "-4"
sendscalenodes.Nodes.Add(masternode)
loadNodes()'load all nodes on pageload
Catch ex As Exception
End Try
End If
End Sub
Protected Sub btndepadd_Click(sender As Object, e As EventArgs) Handles btndepadd.Click
'add nodes code here
loadNodes()'reload all nodes to refresh the tree view
End Sub
Sub loadNodes()
DepGr1.Nodes.Clear()
dbconnection.connect()
masternode = New TreeNod
masternode.Text = "Data Management"
masternode.Value = "Data Management"
masternode.SelectAction = TreeNodeSelectAction.None
DepGr1.Nodes.Add(masternode)
Dim dr As SqlClient.SqlDataReader
Dim dr2 As SqlClient.SqlDataReader
Dim sql2 As String = Nothing
sql = "select * from [data group] where DG_parent=-3"
dr = dbconnection.dr(sql)
Do While dr.Read
parentnod = New EleapTreeNod
parentnod.Text = dr.Item(4)
parentnod.Value = dr("DG_ID")
DepGr1.Nodes.Add(parentnod)
sql2 = " select * from [data group] where DG_parent=" & dr.Item(0) & ""
dr2 = dbconnection.dr(sql2)
Do While dr2.Read
childnod = New EleapTreeNod
childnod.Text = dr2.Item(4)
childnod.Value = dr2("DG_ID")
parentnod.ChildNodes.Add(childnod)
Loop
dr2.Close()
Loop
dr.Close()
dbconnection.ConClose()
DepGr1.ExpandAll()
End Sub

Visual Basic ASP.NET 4 Request.Form()

this may sound like a silly question but i am learning Visual Basic ASP.NET 4 and i have been asked to create a DropDownList which obtains information from a table using SQL. I cant seem to pull the selected item from the dropdownlist and show it on the screen using Request.Form.
I have tried this..
Dim selItem As String = Request.Form("DDList")
Response.Write(selItem)
but this does not show anything on screen. Please help as i am struggling with this.
I have added my dropdownlist as follows:
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>
My Class/Function
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
What i am using on my .aspx.vb page;
Dim dsData1 As New DataSet
dsData1 = tableData()
DDList.DataSource = dsData1
DDList.DataValueField = "code"
DDList.DataTextField = "description"
DDList.DataBind()
DDList.Items.Insert(0, New ListItem(String.Empty, String.Empty))
DDList.SelectedIndex = 0
You don't need to get the selected value using Request.Form if you are using an asp:DropDown ASP.net control. All you have to do is:
Dim selItem As String = DDList.SelectedValue
Response.Write(selItem)
If you really want to use Request.Form, do it like this:
Dim selItem As String = Request.Form(DDList.ClientID)
Response.Write(selItem)
Also, make sure you have ViewState enabled and that you do not rebind the DropDown at PageLoad when there is a PostBack:
Sub Page_Load
If Not IsPostBack
' Bind your DropDown here
End If
End Sub

Problem calling a stored procedure from VB.NET

I am pretty new to VB and I am not sure why this is not working, basically I am trying to run a stored procedure from my web code. The sp runs just fine in SQL, I've tried it several times so I am sure that is not the problem. I don't want to return any results, I just want to see an "ok" statement if it runs and an error message if it doesn't. The code I am using for the lables (warnings and confirmation) is reused from earlier on the same page, the same goes for the validations (valUpload). I am sure the solution is simple...
Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
Try
Dim bl As New BL.ORG
Dim db As Database = DatabaseFactory.CreateDatabase("MyConnection")
Dim dbCommand As DbCommand
db = DatabaseFactory.CreateDatabase("MyConnection")
dbCommand = db.GetStoredProcCommand("Company.dbo.uspMyStoredProcedure")
dbCommand.CommandTimeout = 300
db.AddInParameter(dbCommand, "ClientID", DbType.String, ddlCompany.SelectedValue)
db.AddInParameter(dbCommand, "startPeriod", DbType.String, ddlStartPeriod.SelectedValue)
db.ExecuteDataSet(dbCommand)
lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
lblWarning.Visible = True
lblConfirmation.Visible = False
Catch ex As Exception
valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
valUpload.IsValid = False
End Try
End Sub
I think the issue here is the line
db.ExecuteDataSet(dbCommand)
From what I can see, the command you want to run is
db.ExecuteNonQuery(dbCommand)
Here is an example site. The code is in C# but I think you can get the basic understanding of it. You could also use a translator on it if you really needed to.
http://msdn.microsoft.com/en-us/magazine/cc188702.aspx#S2
I would rewrite it to something similar to this:
Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
Using cnn As New SqlClient.SqlConnection("MyConnection")
cnn.Open()
Using cmd As New SqlClient.SqlCommand("Company.dbo.uspMyStoredProcedure", cnn)
cmd.CommandTimeout = 30
cmd.Parameters.Add(New SqlClient.SqlParameter("ClientID", SqlDbType.NVarChar, 50) With {.Value = ddlCompany.SelectedValue})
cmd.Parameters.Add(New SqlClient.SqlParameter("startPeriod", SqlDbType.NVarChar, 50) With {.Value = ddlStartPeriod.SelectedValue})
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
valUpload.IsValid = False
End Try
lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
lblWarning.Visible = True
lblConfirmation.Visible = False
End Using
End Using
End Sub
A few notes:
Wrap as little code as possible in a try-catch. In this case, only the database should be a cause of concern (granted you validated the inputs).
The using statement very neatly disposes your connection and command objects in case of problems.
You probably want to refactor the code even futher, keeping the database-calling section in a separate function/sub, and setting labels and UI messages somewhere else.

Resources