sending a variable from code-behind to .aspx - asp.net

How I can send a variable from code-behaind to .aspx file :
code-behind:
variable FilePathName
.aspx:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Text="Label"></asp:TextBox>
<frameset cols="100%,*">
<frame name="main" target="main" src="FilePathName">
</frameset>
</div>
</form>
How I can send FilePathName to src in .aspx
Thanks,
Ahmed.
*********** U P D A T E ***********
This is Code-Behind and my goal is to open .pdf file in a frame so that I can open together with another .htm page in one window:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sFilePath As String
Dim buffer As Byte()
Using con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings()("SqlServerConnection").ConnectionString
con.Open()
Using cmd As New SqlCommand("SELECT imageLaw FROM Laws WHERE ID = #ID", con)
Dim pID As New SqlParameter("#ID", SqlDbType.Int)
pID.Value = CType(Request.QueryString("pID"), Integer)
cmd.Parameters.Add(pID)
buffer = cmd.ExecuteScalar()
End Using
con.Close()
End Using
sFilePath = System.IO.Path.GetTempFileName()
System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
System.IO.File.WriteAllBytes(sFilePath, buffer)
'Literal1.Text = "<frame src=\"" + sFilePath + " \ ">"
'TextBox1.Text = sFilePath
' ''Response.WriteFile(sFilePath)
' ''Response.End()
' ''Response.BinaryWrite(buffer)
'Dim act As Action(Of String) = New Action(Of String)(AddressOf OpenFilePW)
'act.BeginInvoke(sFilePath, Nothing, Nothing)
End Sub
Private Shared Sub OpenFilePW(ByVal sFilePath As String)
Using p As New System.Diagnostics.Process
p.StartInfo = New System.Diagnostics.ProcessStartInfo(sFilePath)
p.Start()
p.WaitForExit()
Try
System.IO.File.Delete(sFilePath)
Catch
End Try
End Using
End Sub
I'm remarking last rows because I don't want .pdf file to be opened outside the web page.

You may use a asp:Literal as container for your frame's HTML, or use the <%= Variable %> tag...
Solution 1 :
<frameset cols="100%,*">
<asp:Literal ID="litFrame" runat="server"></asp:Literal>
</frameset>
and in CB : litFrame.Text = "<frame name=\"main\" target=\"main\" src=\"" + FilePathName + "\">";
Solution 2 :
In ASPX :
<frameset cols="100%,*">
<frame name="main" target="main" src="<%= myTarget %>">";
</frameset>
PS : frames are deprecated in web since more than 10 years...

Related

How to check the file is already uploaded or not by using Ajax File Upload?

I am asking a question about Ajax File Upload again.. T_T
I have an ASP.NET webform (using VB.NET) which is using Ajax File Upload. I update my database table whenever I upload a file. I am checking a file is already uploaded or not when I drag into my upload panel and click the upload button.
If the target file is already uploaded, I want to show my error label like 'the file is already uploaded' . But the label doesn't showing . I did debug to trace the result and the file is really existing and it went through my label text setting but didn't show on my form.
Which part of my code is being wrong? I hope someone can guide me.
here is my asp code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
//customize the drag panel
function AjaxFileUpload_change_text() {
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "Click Upload";
document.getElementsByClassName('ajax__fileupload_uploadbutton')[0].style.width = '100px';
}
</script>
<div style="width:40%;padding:25px;margin-left:200px">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" AllowedFileTypes="pdf" MaximumNumberOfFiles="10" />
<asp:Button ID="cmdDone" runat="server" Text="Done" style="display:none" ClientIDMode="Static" />
<script>
function MyCompleteAll() {
$('cmdDone').click()
}
</script>
</div>
<asp:Label ID="lblmsg" runat="server" Text="" Width ="150px" style="color:red"></asp:Label><br />
</asp:Content>
.vb code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "AjaxFileUpload_change_text();", True) //customize ajax panel
lblmsg.Text = "" //error display
End Sub
Protected Sub MyCompleteAll(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim filename As String = e.FileName.Split(".").First + "_" + fileupload + ".pdf"
Dim path As String = Server.MapPath("~/uploads/")
//to add a database table of files up-loaded.
Dim constr As String = CONN + g_schema
Using con As New MySqlConnection(constr)
con.Open()
'check file is already uploaded
Dim select_seq As String = "select fname from filetable where fname like '" +
e.FileName.Split(".").First + "%'"
Dim cmd As New MySqlCommand(select_seq, con)
Dim reader = cmd.ExecuteReader()
While reader.Read()
fname = reader(0).ToString
End While
con.Close()
//the file is already uploaded
If fname IsNot "" Then
lblmsg.Text = "Already uploaded. Please upload the other files."
Else
// Upload process code
End Sub
Thank you.
I going to suggest you check the file on the file upload done event.
So, we can THEN build up a list of files that exist - you have the possibility of more then one file up-load.
So, I suggest dropping in a text box to "hold" each bad (duplicate) file.
So, lets persist into session() the duplicate files (we can NOT use controls on the page in the 3 events (start, complete, complete all).
So, we have this code:
Dim DupList As New List(Of String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("DupList") = DupList
txtDups.Visible = False
Else
DupList = Session("DupList")
End If
End Sub
And say this markup - the text box, a grid view, and of course the FileUpload.
So, say this markup up:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384"
/>
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
<asp:TextBox ID="txtDups" runat="server" TextMode="MultiLine" Width="523px"></asp:TextBox>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table" DataKeyNames="ID"></asp:GridView>
</div>
So far - VERY good you have that JavaScript button click to get our VERY imporant and needed final post back when done.
So, a single file upload done event - looks like this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
' now code to add say to a database table of files up-loaded.
' but FIRST CHECK if the file already exists
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now add to database
Dim NewRow As DataRow = rstFiles.NewRow
NewRow("FileName") = e.FileName
NewRow("UpLoadTime") = Date.Now
NewRow("User_id") = 1
NewRow("Size") = e.FileSize
NewRow("SavePath") = Path.GetDirectoryName(strFileSave) ' get path only
rstFiles.Rows.Add(NewRow)
MyRstUpdate(rstFiles, "MyUpLoadFiles")
End If
End Sub
So note in above HOW WE SKIP the file if it exists. And of course if it does exist, then we of course don't make an entry in the MyFilesUpLoad table.
Ok, so all files up-load - that js button click fires, and we now have this final code stub run:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
' this final code is triggered by the javascrpt "click" on
' all file uplaod done
' if there are some duplicates - dispay to user.
If DupList.Count > 0 Then
txtDups.Visible = True
For Each s As String In DupList
If txtDups.Text <> "" Then txtDups.Text &= vbCrLf
txtDups.Text &= s & " already exists - skipped and not uploaded"
Next
End If
' now addtonal code - maybe display gird of up-loaded files
Dim strSQL As String = "select * from MyUpLoadFiles where UpLoadTime >= #D"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#D", SqlDbType.DateTime).Value = Date.Today
Gfiles.DataSource = MyRstP(cmdSQL)
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub
So, it will look like this:
We hit ok, and now we have/see this:
Ok, so now lets try to re-upload two files that exist.
We So, we will see this:
So, we persist that "bad" list, and skip/don't save the file in the complete event.
And here are the two data helper routines - I don't think it needs much suggesting that one gets VERY tired VERY fast by having to type over and over some simple code to get data into a table - so I used these two helper routines to save World poverty and a few keyboards
Public Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using cmdSQL
Using conn = New SqlConnection(My.Settings.TEST4)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Public Sub MyRstUpdate(rst As DataTable, strTable As String)
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * from " & strTable, conn)
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
conn.Open()
da.Update(rst)
End Using
End Using
End Sub
Edit: Check for "confirmed" file
Follow up question was not only does the file exist, but at some point (or some how - not yet disclosed), the use has the means to check box, or change the status of the up-loaded files. And if file has not yet been confirmed, then we still allow up-loading.
So, the code in question would be this:
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F
AND Confirmed = 9"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists.
' file is confirmed - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it - (or not confirmed)

How to open pdf file in new tab in asp.net(vb)?

I want to show my pdf file in new tab when I click the button of gridview. How can I display? Please someone help me .
This is my code.
'my gridview button click event
Protected Sub btnDisplay_Click(sender As Object, e As EventArgs)
Dim grdrow As GridViewRow = CType((CType(sender, Button)).NamingContainer, GridViewRow)
'I save pdf with datetime but showing file name without datetime on screen so I need to
'combine again when I need to open the file from upload folder
Dim dtime As DateTime = grdrow.Cells(2).Text
Dim fname As String = lblFileName.Text.Split(".").First + "_" +
dtime.ToString("yyyyMMddHHmmss") + ".pdf"
Dim FilePath As String = Server.MapPath("~/uploads/" & fname)
Dim User As WebClient = New WebClient()
Dim FileBuffer As Byte() = User.DownloadData(FilePath)
If FileBuffer IsNot Nothing Then
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", FileBuffer.Length.ToString())
Response.BinaryWrite(FileBuffer)
End If
End Sub
--Edit--
I got some idea and it did work for me.
I added some script to open new tab.
html,gridview
//javascript
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
<asp:BoundField DataField="FileName" HeaderText="Filename" ItemStyle-Width="200" HtmlEncode="false"><ItemStyle Width="200px"></ItemStyle></asp:BoundField>
<asp:BoundField DataField="Process" HeaderText="Process" ItemStyle-Width="200" HtmlEncode="false"><ItemStyle Width="200px"></ItemStyle></asp:BoundField>
<asp:TemplateField ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" OnClientClick="openInNewTab();" Visible='<%# If(Eval("Process").ToString() = "Uploaded", True, False) %>'></asp:Button>
</ItemTemplate>
</asp:TemplateField>
Main.aspx
Protected Sub btnDisplay_Click(sender As Object, e As EventArgs)
Dim grdrow As GridViewRow = CType((CType(sender, Button)).NamingContainer, GridViewRow)
Dim fname As String = grdrow.Cells(2).Text
'pdf Display
Session("pdfname") = fname
Response.Redirect("GeneratePDF.aspx")
End Sub
GeneratePDF.aspx
<form id="form1" runat="server">
<div style ="Display: Inline-block;float: left;">
<asp:Literal ID="ltEmbed" runat="server" />
</div>
</form>
GeneratePDF.aspx.vb
Dim pdf_name As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.Title = "PDF DISPLAY"
pdf_name = Session("pdfname")
Dim embed As String = "<object data=""{0}"" type=""application/pdf"" width=""2000px"" height=""1000px"">"
embed += "If you are unable to view file, you can download from here"
embed += " or download <a target = ""_blank"" href = ""http://get.adobe.com/reader/"">Adobe PDF Reader</a> to view the file."
embed += "</object>"
ltEmbed.Text = String.Format(embed, ResolveUrl("~/uploads/" + pdf_name))
End Sub
First use hyperlink instead of Button and make target =_blank. Then on Page Load of new aspx write code for generating PDF.
'HTML CODE
<asp:HyperLink ID="btnDisplay" runat="server" Text="Open PDF" Target ="_blank" NavigateUrl="~/WBP/GeneratePDF.aspx"></asp:HyperLink>
'SERVER CODE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim dtime As DateTime = DateTime.Now.ToString()
Dim fname As String = "pdffile_" +
dtime.ToString("yyyyMMddHHmmss") + ".pdf"
Dim FilePath As String = Server.MapPath("writereaddata/" & fname)
Dim User As WebClient = New WebClient()
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Dim pdfDoc As New Document(PageSize.A4, 10, 10, 8, 2)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream)
Dim sr As New StringReader(sw.ToString())
pdfDoc.Open()
Dim pthd As Paragraph = New Paragraph("WELCOME TO PDF FILE", New Font(Font.TIMES_ROMAN, 11, Font.BOLD, Color.BLACK))
pdfDoc.Add(pthd)
htmlparser.Parse(sr)
pdfDoc.Close()
HttpContext.Current.Response.Write(pdfDoc)
HttpContext.Current.Response.End()
End Sub
i think you are missing something, add Response.End() at the end of the if statement
If FileBuffer IsNot Nothing Then
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", FileBuffer.Length.ToString())
Response.BinaryWrite(FileBuffer)
Response.End()
End If
if it doesnt work, there must be an issue on the Html

Decoding HTML and databinding into a ASP.NET repeater

I have a separate page where I use the Server.HTMLEncode feature to encode HTML a user has entered inside of a HTMLEditorExtender on a TextBox.
I am trying to insert this HTML into a repeater like so:
<asp:Repeater id="articleList" runat="server">
<ItemTemplate>
<div class="itemtemplate">
<h2><%#Container.DataItem("Title")%></h2>
<h5>Category:</h5> <%#Container.DataItem("Category")%><br />
<%#Container.DataItem("decodedHTML")%>
<%#Container.DataItem("UserName")%>
<%#Container.DataItem("DateOfPost")%>
</div>
</ItemTemplate>
<AlternatingItemTemplate>
<div class="altitemtemplate">
<h2><%#Container.DataItem("Title")%></h2>
<h5>Category:</h5> <%#Container.DataItem("Category")%><br />
<%#Container.DataItem("decodedHTML")%>
<%#Container.DataItem("UserName")%>
<%#Container.DataItem("DateOfPost")%>
</div>
</AlternatingItemTemplate>
</asp:Repeater>
And my code behind:
Sub displayArticles()
Dim conn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
conn.Open()
Dim cmd As New OleDbCommand("SELECT * FROM [UserArticles] ORDER BY DateOfPost DESC", conn)
Dim inputString As String = "HTMLBody"
Dim decodedHTML As String = Server.HtmlDecode(inputString)
articleList.DataSource = cmd.ExecuteReader()
articleList.DataBind()
conn.Close()
End Sub
"HTMLBody" is the name of the field in my database with the encoded HTML in.
Unfortunately, I am receiving the error
"IndexOutOfRangeException was unhandled by user code".
There is obviously a problem here referring to the string decodedHTML in my Container.DataItem statement, so what am I doing wrong?
EDIT: code from the other page where the html is encoded:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If String.IsNullOrEmpty(TextBox1.Text) Then
ErrorMessage.Visible = True
ErrorMessage.Text = "Your submission is blank. Please write your article first"
Else
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into UserArticles(Title,Category,UserName,DateOfPost,HTMLPost) Values (#f1,#f2,#f3,#f4,#f5)"
Dim HTMLEncode As String = Server.HtmlEncode(TextBox1.Text)
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", ArticleTitle.Text)
cmd.Parameters.AddWithValue("#f2", CategoryDropDown.SelectedValue)
cmd.Parameters.AddWithValue("#f3", User.Identity.Name)
cmd.Parameters.AddWithValue("#f4", DateTime.Now.Date)
cmd.Parameters.AddWithValue("#f5", HTMLEncode)
oleDbConn.Open()
cmd.ExecuteNonQuery()
TextBox1.Text = Nothing
ArticleTitle.Text = Nothing
CategoryDropDown.ClearSelection()
End If
End Sub
From the looks of it, decodedHTML is just a string which you are creating in the code. This is not accessible through your .aspx page.
You should just be able to update your .aspx markup to;
<%#Server.HtmlDecode(Container.DataItem("[COLUMN_NAME"))%>
Where [COLUMN_NAME] is the actual Table Column which holds the encoded html value.

Passing Value doesn't appear?

I am new at ASP.net and VB.net.So i Learn from book beginning ASP.Net 3.5 in VB 2008
the code on select.aspx.vb are
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Partial Public Class _Select
Inherits System.Web.UI.Page
Private Conn As String = WebConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
FillAuthorList()
End If
End Sub
Private Sub FillAuthorList()
lstAuthor.Items.Clear()
' Define the Select statement.
' Three pieces of information are needed: the unique id
' and the first and last name.
Dim selectSQL As String = "SELECT Nama_Depan, Nama_Belakang, ID FROM Employee"
' Define the ADO.NET objects.
Dim con As New SqlConnection(Conn)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
' For each item, add the author name to the displayed
' list box text, and store the unique ID in the Value property.
Do While reader.Read()
Dim newItem As New ListItem()
newItem.Text = reader("Nama_Depan") & ", " & reader("Nama_Belakang")
newItem.Value = reader("ID").ToString()
lstAuthor.Items.Add(newItem)
Loop
reader.Close()
Catch err As Exception
lblResults.Text = "Error reading list of names."
lblResults.Text &= err.Message
Finally
con.Close()
End Try
End Sub
Protected Sub lstAuthor_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstAuthor.SelectedIndexChanged
' Create a Select statement that searches for a record
' matching the specific author ID from the Value property.
Dim selectSQL As String
selectSQL = "SELECT * FROM Employee "
selectSQL &= "WHERE ID='" & lstAuthor.SelectedItem.Value & "' "
' Define the ADO.NET objects.
Dim con As New SqlConnection(Conn)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
reader.Read()
' Build a string with the record information,
' and display that in a label.
Dim sb As New StringBuilder()
sb.Append("<b>")
sb.Append(reader("Nama_Depan"))
sb.Append(", ")
sb.Append(reader("Nama_Belakang"))
sb.Append("</b><br />")
lblResults.Text = sb.ToString()
reader.Close()
Catch err As Exception
lblResults.Text = "Error getting author. "
lblResults.Text &= err.Message
Finally
con.Close()
End Try
End Sub
End Class
And the select.aspx are
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Select.aspx.vb" Inherits="connn._Select" %>
<!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">
<div>
<asp:ListBox ID="lstAuthor" runat="server" ></asp:ListBox>
<br />
<asp:Label ID="lblResults" runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
I am trying when select Listbox with ID="lstAuthor" the label box will pass the value but it failed to show.
Set True to AutoPostBack property:
<asp:ListBox ID="lstAuthor"
runat="server"
AutoPostBack="True" ></asp:ListBox>

ASP.NET, VB.NET, and Database Issue

I am trying to learn how to do this .NET frameworks for my job and what not..... I can't figure why it isn't working.
Error occurs here:
myCommand.Connection.Open()
I am assuming it is because of how I am doing....
Dim idbox As TextBox = E.Item.Cells(numCols - 1).Controls(0)
myCommand.Parameters("#Id").Value = Integer.Parse(idbox.Text)
Source:
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Data.OleDb" %>
<html>
<script language="VB" runat="server">
Dim myConnection As SqlConnection
' Create a connection to the "pubs" SQL database located on the
' local computer.
Sub Page_Load(Src As Object, E As EventArgs)
If Session("Admin") <> True Then
Response.Redirect("login.aspx")
Else
Dim myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
' Determine whether this page is a postback. If it is not a
' postback, call BindGrid.
If Not IsPostBack Then
Dim dbconn As OleDbConnection
Dim sql As String
Dim dbcomm As OleDbCommand
Dim dbread As OleDbDataReader
dbconn = New OleDbConnection("CONNECTION INFO")
dbconn.Open()
sql = "SELECT Name FROM TestData"
dbcomm = New OleDbCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
DropDownList1.Items.Clear()
While dbread.Read
DropDownList1.Items.Add(dbread(0))
End While
dbread.Close()
dbconn.Close()
BindGrid()
End If
End If
End Sub
' Create an index to the DataGrid row that is clicked and
' call BindGrid.
Sub MyDataGrid_Edit(sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = CInt(E.Item.ItemIndex)
BindGrid()
End Sub
' Cancel resets the index to the row's previous settings.
Sub MyDataGrid_Cancel(sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = -1
BindGrid()
End Sub
' When the Update link is clicked, build a SQL UPDATE command,
' connect to the database, update the row's information in the
' database, and rebind the DataGrid to show the updated information.
Public Sub MyDataGrid_Update(sender As Object, _
E As DataGridCommandEventArgs)
Dim updateCmd As String = "UPDATE TestData SET AdoptedNum = #AdoptedNum, PrecinctNum = #PrecinctNum WHERE Id = #Id"
Dim myCommand As SqlCommand = New SqlCommand(updateCmd, myConnection)
myCommand.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
myCommand.Parameters.Add(New SqlParameter("#PrecinctNum", SqlDbType.Int))
myCommand.Parameters.Add(New SqlParameter("#AdoptedNum", SqlDbType.Int))
myCommand.Parameters.Add(New SqlParameter("#Id", SqlDbType.Int))
' Initialize the SqlCommand "#ID" parameter to the ID of the row
' that must be clicked.
Dim numCols As Integer = E.Item.Cells.Count
Dim i As Integer
Dim colvalue As String
Dim txtBox As TextBox
Dim idbox As TextBox = E.Item.Cells(numCols - 1).Controls(0)
myCommand.Parameters("#Id").Value = Integer.Parse(idbox.Text)
' Create an array of column names.
Dim cols() As String = {"#Name", "#PrecinctNum", "#AdoptedNum", "#Id"}
' Skipping the first, second, and last columns, iterate through the
' columns, checking for empty values. If an empty value is found,
' display a message box. Also initialize the SqlCommand
' parameter values.
For i = 2 To numCols - 1
txtBox = E.Item.Cells(i).Controls(0)
colvalue = txtBox.Text
If (i < numCols And colvalue = "") Then
Message.InnerHtml = "ERROR: Null values not allowed for " _
& "Author ID, Name or Phone"
Message.Style("color") = "red"
Exit Sub
End If
myCommand.Parameters(cols(i - 1)).Value = colvalue
Next i
' Connect to the database and update the information.
myCommand.Connection.Open()
' Test whether the data was updated, and display the
' appropriate message to the user.
Try
myCommand.ExecuteNonQuery()
Message.InnerHtml = "<b>Record Updated.</b><br>"
MyDataGrid.EditItemIndex = -1
Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists" _
& " with the same primary key"
Else
Message.InnerHtml = "ERROR: Could not update record," _
& " please ensure the fields are correctly filled out."
Message.Style("color") = "red"
End If
End Try
' Close the connection.
myCommand.Connection.Close()
' Rebind the DataGrid to show the updated information.
BindGrid()
End Sub
' The BindGrid procedure connects to the database and implements
' a SQL SELECT query to get all the data in the "Authors" tablea.
Public Sub BindGrid()
Dim myConnection As SqlConnection = _
New SqlConnection("CONNECTION INFO")
Dim myCommand As SqlDataAdapter = New SqlDataAdapter("SELECT *" _
& " FROM TestData WHERE Name='" & DropDownList1.SelectedValue & "'", myConnection)
Dim ds As DataSet= New DataSet()
myCommand.Fill(ds)
MyDataGrid.DataSource = ds
MyDataGrid.DataBind()
End Sub
Protected Sub MyDataGrid_SelectedIndexChanged(sender As Object, e As System.EventArgs)
End Sub
Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
BindGrid()
End Sub
</script>
<body style="font: 10pt verdana">
<form id="Form1" runat="server"><center>
<h3><font face="Verdana">Updating a Row of Data.</font></h3>
<span id="Message" EnableViewState="false"
style="font:arial 11pt;" runat="server"/><p>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="800"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
OnEditCommand="MyDataGrid_Edit"
OnCancelCommand="MyDataGrid_Cancel"
OnUpdateCommand="MyDataGrid_Update"
>
<Columns>
<ASP:EditCommandColumn EditText="Edit" CancelText="Cancel"
UpdateText="Update"/>
</Columns>
</ASP:DataGrid>
</center>
</form>
</body>
</html>
I suspect the problem is you define but never initialize the instance variable myConnection. You define and instantiate a local variable of the same name within the Page_Load function, but that is a distinct and different object than your instance variable.
In your Page_Load, if you change this:
Dim myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
to this:
myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
then your instance variable should be initialized and ready for use in your MyDataGrid_Update event handler.
Did this even compile? This wont work because your code has a bug.
SqlCommand won't support myCommand.Connection.Open()

Resources