A continuation of the question on display (not download) image from db
<%# Page Language="VB" AutoEventWireup="false" CodeFile="imgTest1.aspx.vb" Inherits="imgTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="background-color: aliceblue;">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<br />
</div>
<div style="background-color: burlywood;">
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?id=1" />
<br />
<br />
<br />
</div>
</div>
</form>
</body>
</html>
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class imgTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("id") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "filename=" & dt.Rows(0)("name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End If
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("CapstoneConnectionString1").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
End Class
I can now display the image on the aspx page but only the image is being displayed, all other web elements are missing.
I can only think of one reason for this, given that following are true:
Page used to render contents is imgTest1.aspx as well as page used to return image is also imgTest1.aspx.
imgTest1.aspx is always invoked with query parameter, id.
because of this page always returns an image.
Can you change the code as follows and tell us how it works:
...
...
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?imageId=1" />
...
...
and in code-behind
If Request.QueryString("imageId") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")
Related
I'm creating a login form in my asp.net page and my problem now is I don't know how to connect my asp.net (vb) to the SQL Server database.
I wanted to insert the connection code in the
<script runat="server"> </script>
Is this possible?
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Login.aspx.vb" Inherits="_Default" %>
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
lblDate.Text = Format(Now, "MMMM dd,yyyy hh:mmtt")
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="icon" type="image/png" href="SENCOR_Logo.ico">
<title>Auto OCS System</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="date_time">
<p><asp:Label id="lblDate" runat="server" Text ="DateandTime"></asp:Label></p>
</div>
<div id="wrapper">
<div class = "container">
<div class = "login">
<h1><img src="SENCOR_Logo.jpg" height="35px;"></h1>
<form method = "post" action = "" runat="server">
<p><asp:TextBox id="txtUser" runat="server" placeholder="Username"/></p>
<p><asp:TextBox id="txtPass" runat="server" TextMode="Password" placeholder="Password"/></p>
<p class = "remember_me">
<label>
<label>
<asp:CheckBox id="chkRem" runat="server"/>
Remember me on this computer
</label>
</label>
</p>
<p class="submit"><asp:Button id="btnLogin" Text="Login" runat="server" OnClick = "btnLogin_Click" /></p>
</form>
</div>
<div class="login-help">
<p>Forget your password? <asp:HyperLink id="lnkRem" runat="server" Text="Click here to reset it." NavigateUrl ="~/Login.aspx"></asp:HyperLink></p>
</div>
</div></div>
<div class="footer">
<p>© 2016 Emilyn Pascua. All rights reserved.</p>
</div>
</body>
</html>
This may help you.change code according to your data
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Passowrd As String
Dim Passowrd2 As String
Dim userName As String
Try
If
/*change the data source and initial catalog according to your sql server engine and data base*/
con.ConnectionString = "Data Source = YOUR-PC; Initial Catalog = YOUR-DB; Integrated Security = True"
con.Open()
cmd.Connection = con
/*change the data fields names and table according to your database*/
cmd.CommandText = " SELECT UserName, Password FROM AdminDetail WHERE (UserName = '" & txtUsername.Text & "' ) AND (Password = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
//Do something here
Passowrd = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Passowrd2 = txtPassword.Text()
If Passowrd = Passowrd2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
frmMain.Show()
Me.Hide()
//Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
//Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() //Whether there is error or not. Close the connection.
End Try
End Sub
I hope you can embed the same in your server tags..you may refer the following link for clarification
http://www.aspsnippets.com/Articles/Different-Embedded-Code-Blocks-and-its-use-in-ASPNet.aspx
String cons = "Data Source=.; initial Catalog=SalaamUnExamSystem; Integrated Security=true";
SqlConnection con = new SqlConnection(cons);
SqlCommand cmd = new SqlCommand("insert into stdtbl values('" + StdName.Text + "','" + FName.Text + "','"+gender+"')",con);
con.Open();
int r=cmd.ExecuteNonQuery();
if (r > 0)
{
lblMessage.Text="inserted";
}
else
{
lblMessage.Text = "Not Inserted";
}
I have found this code and I slightly re-writte it. I want that when I select order value from dropdown list, is showing customer in text below.
I have to say, that I have very little VB programming experience, so I'm stuck here.
Code:
<%# Page Language="VB" Debug="True" Strict="True" %>
<%# Import Namespace="System.Data.Odbc" %>
<%# Import Namespace="System.Data" %>
<%# import Namespace="System.Data.SqlClient" %>
<font face="calibri">
<script runat="server">
Dim connStr As String = "server=MSSQLEXP;database=ppwin1;Uid=sa_ro;pwd=sa_ro"
Sub Userlist_Init(ByVal Sender As Object, ByVal E As EventArgs)
Dim conn As New SqlConnection(connStr)
conn.Open()
Dim sql_user As String
Dim cmd_user As Sqlcommand
sql_User = "SELECT DISTINCT order, customer FROM dbo.T_CUSTOMER ORDER BY order ASC"
cmd_user = New Sqlcommand (sql_user, conn)
finduser.Datasource=cmd_user.ExecuteReader()
finduser.datatextfield = "customer"
finduser.databind()
conn.Close()
End Sub
Sub Finduser_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
txtuser.text = finduser.selecteditem.text
End sub
</script>
<html><head><title>Dropdown list from MS SQL DB</title></head>
<body><h1>Dropdown list from MS SQL DB</h1>
<br>
<form runat="server">
<asp:DropDownList ID="finduser" runat="server" AutoPostBack = "true" OnSelectedIndexChanged="Finduser_SelectedIndexChanged" OnInit="userlist_Init">
</asp:DropDownList>
<asp:Label id="txtuser" runat="server" />
</form>
</body>
</html>
Rok
Instead of this
finduser.Datasource = cmd_user.ExecuteReader()
finduser.datatextfield = "customer"
finduser.databind()
Did you tried this?
Dim dr As SqlClient.SqlDataReader = cmd_user.ExecuteReader
finduser.Items.Clear()
While dr.Read()
finduser.Items.Add(new ListItem(dr("customer"),dr("order"))
End While
OR
Dim dr As SqlClient.SqlDataReader
dr = cmd_user.ExecuteReader
Dim myData as New DataTable
If dr.HasRows Then
myData.Load(dr)
End If
ddldept.datasource = myData
ddldept.DataTextField = "customer"
ddldept.DataValueField = "order"
ddldept.DataBind()
I have a simple web application that is reading records from a CSV file and storing them in a database table. Then I am using SqlBulkCopy to copy the records into an SQL database using batches. All is fine with the insert. I am trying to give the user some feedback using OnSqlRowsCopied and NotifyAfter. The goal is to update a label that is contained in an UpdatePanel to display the number of records copied at the current NotifyAfter interval. However, the label will not update until SqlBulkCopy has complete. I can see that the s_OnSqlRowsCopied event is firing using Debug.WriteLine. What is the reason why the label won't update and how can I overcome this?
Code Behind
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim filePath As String
Dim rowsCopied As String
Public Sub btnGetCSV_Click(sender As Object, e As EventArgs) Handles btnGetCSV.Click
filePath = System.IO.Path.GetFullPath(fileUpload1.PostedFile.FileName)
lblInfo.Text = filePath
End Sub
Protected Sub btnToSQL_Click(sender As Object, e As EventArgs) Handles btnToSQL.Click
Dim cs As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("csMediaPortal").ConnectionString
CopyData(CSVtoDataTable(lblInfo.Text.ToString()), cs)
End Sub
Private Function CSVtoDataTable(filePath As String) As DataTable
Dim dt As DataTable = Nothing
Dim sourcePath As String = String.Empty
Dim csvFile As String = String.Empty
Dim conString As String = String.Empty
Dim conn As OleDb.OleDbConnection = Nothing
Dim adapter As OleDb.OleDbDataAdapter = Nothing
Dim selString As String = String.Empty
Try
sourcePath = System.IO.Path.GetDirectoryName(filePath)
csvFile = System.IO.Path.GetFileName(filePath)
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourcePath & ";Extended Properties=""text;HDR=No;FMT=FixedLength"""
conn = New OleDb.OleDbConnection(conString)
selString = "Select * From " & csvFile
adapter = New OleDb.OleDbDataAdapter(selString, conn)
dt = New DataTable(System.IO.Path.GetFileNameWithoutExtension(filePath))
conn.Open()
adapter.Fill(dt)
conn.Close()
Catch ex As Exception
lblInfo.Text = ex.Message
Finally
adapter.Dispose()
conn.Dispose()
End Try
Return dt
End Function
Protected Sub CopyData(sourceTable As DataTable, cs As String)
Using s As SqlBulkCopy = New SqlBulkCopy(cs, SqlBulkCopyOptions.UseInternalTransaction)
s.DestinationTableName = "test"
s.BatchSize = 1000
Try
AddHandler s.SqlRowsCopied, AddressOf s_OnSqlRowsCopied
s.NotifyAfter = 900
s.WriteToServer(sourceTable)
Catch ex As Exception
DirectCast(DirectCast(HttpContext.Current.Handler, Page).FindControl("lblInfo"), Label).Text = "Commit Error: " & ex.Message
End Try
s.Close()
End Using
End Sub
Protected Sub s_OnSqlRowsCopied(sender As Object, e As SqlRowsCopiedEventArgs)
Me.lblProgress.Value = e.RowsCopied.ToString()
Me.UpdatePanel1.Update()
Debug.WriteLine(e.RowsCopied)
End Sub
End Class
Web Form
<%# Page Language="vb" CodeBehind="WebForm1.aspx.vb" Inherits="CSVUpload.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:FileUpload ID="fileUpload1" runat="server" />
<asp:Button ID="btnGetCSV" runat="server" Text="Post" OnClick="btnGetCSV_Click" />
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
</div>
<asp:Button ID="btnToSQL" runat="server" Text="Insert To SQL" OnClick="btnToSQL_Click" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<input runat="server" type="text" id="lblProgress" value="0" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
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)
Edit for vhinn
I want it to look like this:
I am trying to build an html table dynamically on pageload with variables from a database.
this is an example strictly html http://jsfiddle.net/jdv590/daCum/1/
code:
Private Sub brothersgird()
Dim html As New StringBuilder
Dim sql As String = "select Name, Hometown, Picture, Class from brothers",
connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;",
conn As New OleDbConnection(connstring),
myCommand As New OleDbCommand(sql, conn),
namevar As String,
classvar As String,
hometownvar As String
Dim x As Integer = 1
conn.Open()
Dim dr As OleDbDataReader = myCommand.ExecuteReader
html.Append("<table>")
Do While dr.Read
' imagevar = dr("Picture")
namevar = dr("Name")
classvar = dr("Class")
hometownvar = dr("Hometown")
html.Append("<tr>")
Do While x < 4
html.Append("<td><p>" & namevar & "<br /> Hometown: " & hometownvar & "<br /> Class: " & classvar & "</p></td>")
x = x + 1
Loop
html.Append("</tr>")
x = 0
Loop
html.Append("</table>")
dr.Close()
conn.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
brothersgird()
'write to panel maybe with this idea:
seniorpanel.html=html ???
End Sub
aspx side:
<asp:Panel ID="seniorpanel" runat="server">
</asp:Panel>
in your markup:
<asp:Panel ID="seniorpanel" runat="server">
<asp:GridView ID="brothersgird" runat="server" ShowHeader="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>
<%# Eval("Name")%><br />
Hometown:
<%# Eval("Hometown")%><br />
Class:
<%# Eval("Hometown")%>
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
brothersgird.DataSource = SelectBrothers()
brothersgird.DataBind()
End If
End Sub
Private Function SelectBrothers() As DataTable
Dim sql As String = "select Name, Hometown, Picture, Class from brothers"
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;"
Dim conn As New OleDbConnection(connstring)
Dim ds As New DataSet
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand(sql, conn)
adapter.Fill(ds)
Return ds.Tables(0)
End Function
You familiar with DataGrids?
Client Side:
<asp:DataGrid runat="server" id="dataTable">
</asp:DataGrid>
Server Side:
//Get your data table from the database - let's say the variable is called dt
dataTable.DataSource = dt
dataTable.DataBind()
There is a lot more you can do with datagrids, but this should be enough to get you started if you decide to go this route.
Are you asking how to do this in javascript if you already have the data? If so an example would be kinda like this:
var row = document.createElement("TR");
var th1 = document.createElement("TH");
row.appendChild(th1);