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>
Related
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.
I'm trying to create a pager in a repeater control. The content is being pulled from the database and is displaying but when I click on the previous and next buttons they don't page, that is, I stay on the same content. Would anyone be able to see the error from the code below? No errors or showing so I think it is something minor but I have been banging my head against a wall trying to find it
Markup:
<asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("MovieID", "Default2.aspx?ArtID={0}")%>'>
<%# DataBinder.Eval(Container.DataItem, "MovieTitle")%>
</asp:HyperLink>
</li>
</ItemTemplate>
Code Behind:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT MovieID, MovieTitle FROM Movies", strConnect)
objOleDBAdapter.Fill(DS, "Movies")
Return DS.Tables("Movies").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 1
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
After banging my head against a wall I found a solution. I forgot to connect the buttons to the repeater control. Here's a solution:
Imports System.Data
Imports System.Data.OleDb
Partial Class Default2
Inherits System.Web.UI.Page
Dim pagedData As New PagedDataSource
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT MovieID, MovieTitle FROM Movies", strConnect)
objOleDBAdapter.Fill(DS, "Movies")
Return DS.Tables("Movies").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 1
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
If Not pagedData.IsFirstPage Then
btnPrev.PostBackUrl = Request.CurrentExecutionFilePath + _
"?Page=" + CStr(pagedData.CurrentPageIndex - 1)
End If
If Not pagedData.IsLastPage Then
btnNext.PostBackUrl = Request.CurrentExecutionFilePath + _
"?Page=" + CStr(pagedData.CurrentPageIndex + 1)
End If
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
How to access controls from class files in app code?
Markup:
<%# Page Language="vb" AutoEventWireup="false" Inherits="shoppingCart1.ShoppingPage" CodeFile="ShoppingPage.aspx.vb" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>ShoppingPage</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server" name="Form1">
<TABLE id="tblShopping" style="FONT-SIZE:10pt;FONT-FAMILY:verdana" borderColor="black"
width="100%" cellSpacing="0" cellPadding="0" border="1" runat="server">
<tr style="FONT-SIZE:10pt;FONT-FAMILY:verdana;color:white;background-color:#336699;font-weight:bold;">
<td colspan="4">PRODUCT LIST</td>
</tr>
<tr>
***<td id="cellshoping" runat="server" colspan="4" width="100%"></td>***
</tr>
<tr>
</tr>
</TABLE>
</form>
</body>
</HTML>
ShoppingCart.vb In App_Code Folder
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ShoppingCart
Public Sub bindData()
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim objDA As SqlDataAdapter
Dim myRow As SqlDataReader
Dim comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
myRow = comd.ExecuteReader()
Dim strRowGen As String = ""
While myRow.Read()
strRowGen = strRowGen & "<TR>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
strRowGen = strRowGen & "</TR>"
**cellshoping**.InnerHtml = strRowGen
End While
End Sub
End Class
I get an error at cellshoping.InnerHtml "cellshoping is not declared"...how to access user controls from class files in app code ??
ADDED ASPX CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Namespace shoppingCart1
Partial Class ShoppingPage
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
Protected WithEvents Label3 As System.Web.UI.WebControls.Label
Protected WithEvents txtNK As System.Web.UI.WebControls.TextBox
Protected WithEvents txtCF As System.Web.UI.WebControls.TextBox
Protected WithEvents txtHA As System.Web.UI.WebControls.TextBox
Protected WithEvents dtGrdProducts As System.Web.UI.WebControls.DataGrid
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Load data by calling function bindData()
Dim sCart = New ShoppingCart
If Not Page.IsPostBack Then
cellshoping.InnerHtml = sCart.bindData()
End If
Dim strQty As Integer
Dim proId As String
Dim delId As String
delId = Request.QueryString("delItemId")
proId = Request.QueryString("itemId")
'------ Following portion act as controller where code is written as
'------ per the action from the request of the pages like Add To Cart,
'------ Update Cart & Delete Cart
strQty = 1
If Request.QueryString("Actn") <> "" Then
If Request.QueryString("Actn").Equals("Add") Then
If Request.QueryString("itemId") <> "" Then
AddToSession(proId, strQty)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Del") Then
If Request.QueryString("delItemId") <> "" Then
Session.Remove(delId)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Update") Then
If Request.QueryString("itemUpId") <> "" And Request.QueryString("quantity") <> "" Then
If IsNumeric(Request.QueryString("itemUpId")) Then
updateCart(Request.QueryString("itemUpId"), Request.QueryString("quantity"))
Response.Redirect("./ShoppingCart.aspx")
Else
Response.Redirect("./ShoppingCart.aspx")
End If
End If
End If
End If
End Sub
Private Sub AddToSession(ByVal strProduct As String, ByVal intQty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(Session(strProduct)) + intQty)
Else
Session.Add(strProduct, intQty)
End If
End Sub
Private Sub updateCart(ByVal strProduct As String, ByVal qty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(qty))
End If
End Sub
End Class
End Namespace
Assuming that the ShoppingCart class is referenced somewhere in the page's code-behind and the BindData() method is called from that code, you have a few choices:
1) Pass a reference to the page to the shopping cart's bind data method.
2) Return the data from the BindData() method to the page so that it can update the data in the page appropriately.
3) You could access HttpContext.Current.Handler and cast that to an instance of your page.
My recommendation, especially if you want to use the class in other pages, is to either create an interface that has a method that can be used to update the data and use options 1 or 3, or implement option 2.
Here is an example of how you would change the code to implement and interface.
The interface:
Public Interface IShoppingCartPage
Sub UpdateData(sCartContents As String)
End Interface
The page codebeghind (partial):
Public Class ShoppingPage
Implements IShoppingCartPage
Public Sub UpdateData(sCartContents As String) Implements IShoppingCartPage.UpdateData
cellshopping.innerHtml = sCartContents
End Sub
End Class
And finally, the modified shopping cart class (note the use of the stringbuilder class, which will be much more efficient than the string concat in the question):
Public Class ShoppingCart
Public Sub bindData(oPage As IShoppingCartPage)
Using con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
Using oReader As SqlDataReader = comd.ExecuteReader()
Dim sbHTML As New System.Text.StringBuilder(5000)
While oReader.Read()
sbHTML.Append("<TR>")
sbHTML.Append("<TD>").Append(oReader.GetValue(0)).Append("</TD>")
sbHTML.Append("<TD>").Append(oReader.GetValue(1)).Append("</TD>")
sbHTML.Append("<TD>").Append(oReader.GetValue(2)).Append("</TD>")
sbHTML.Append("<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=").Append(oReader.GetValue(0)).Append("';document.Form1.submit();"">Add To Cart</TD>")
sbHTML.Append("</TR>")
End While
oPage.UpdateData(sbHTML.ToString())
End Using
End Using
con.Close()
End Using
End Sub
End Class
Why not have your method return a string?
Public Function bindData() as String
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim objDA As SqlDataAdapter
Dim myRow As SqlDataReader
Dim comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
myRow = comd.ExecuteReader()
Dim strRowGen As String = ""
While myRow.Read()
strRowGen = strRowGen & "<TR>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
strRowGen = strRowGen & "</TR>"
End While
Return strRowGen
End Sub
Then you can call it from your page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'Set innerHtml here
'cellshoping.InnerHtml = ShoppingCart.bindData()
End Sub
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()
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...