I am trying to populate textbox fields from an excel sheet using vb.net.
I have the following code:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server"
Height="21px" Text="Upload"
Width="92px" onclick="btnUpload_Click"/>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
Using the Fileupload a user can upload an excel sheet, Which will then extract the information to populate some fields.
My first step is trying to get it to databind with the grid view on button click to which I am having no luck: Using the following:
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
Dim connectionString As String = ""
If FileUpload1.HasFile Then
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/App_Data/" & fileName)
FileUpload1.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
End If
'Create OleDB Connection and OleDb Command
Dim con As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim dAdapter As New OleDbDataAdapter(cmd)
Dim dtExcelRecords As New DataTable()
con.Open()
Dim dtExcelSheetName As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim getExcelSheetName As String = dtExcelSheetName.Rows(0)("Table_Name").ToString()
cmd.CommandText = "SELECT * FROM [" & getExcelSheetName & "]"
dAdapter.SelectCommand = cmd
dAdapter.Fill(dtExcelRecords)
con.Close()
GridView1.DataSource = dtExcelRecords
GridView1.DataBind()
End If
End Sub
To which I am getting the error "Access to the path 'C:\inetpub\wwwroot\Portal\docs\Encoding_Time.csv' is denied.
", which makes me ask where does the file upload control save the file?
UPDATE: I am now getting the following error "The ConnectionString property has not been initialized."
Related
it have been a week since I start with this project but I'm totally clueless on what to fix anymore. down here is part of my coding.
Protected Sub bpn_Click(sender As Object, e As EventArgs)
Try
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SQLServer2005DBConnectionString").ToString())
connection.Open()
Dim sql As String = ("select * from LOT_ WHERE PRODUCTNAME ='" & txtbpn.Text & "'")
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
Using reader As SqlDataReader = cmd.ExecuteReader
If reader.HasRows Then
lblerror.Visible = False
connection.Dispose()
connection.Close()
Me.BindBpn()
txtbpn.Text = String.Empty
TextBox2.Text = String.Empty
TextBox3.Text = String.Empty
TextBox4.Text = String.Empty
TextBox5.Text = String.Empty
Else
connection.Dispose()
connection.Close()
lblerror.Text = "bpn not found"
lblerror.Visible = True
txtbpn.Text = String.Empty
TextBox2.Text = String.Empty
TextBox3.Text = String.Empty
TextBox4.Text = String.Empty
TextBox5.Text = String.Empty
End If
End Using
Catch ex As Exception
Response.Write(ex.Message)
Response.AppendHeader("Refresh", "1;url=Summary.aspx")
End Try
End Sub
1.the binding sub
Private Sub BindBpn()
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("SQLServer2005DBConnectionString").ToString())
Using cmd As New SqlCommand("SELECT * FROM LOT_ WHERE PRODUCTNAME='" & txtbpn.Text & "'order by checkin asc")
Using sda As New SqlDataAdapter()
con.Open()
cmd.Connection = con
sda.SelectCommand = cmd
Dim dt As New DataTable()
sda.Fill(dt)
Dim dv As New DataView(dt)
GridView1.DataSource = dv
GridView1.DataBind()
' Me.BindGridView()
con.Close()
End Using
End Using
End Using
If GridView1.Visible = False Then
GridView1.Visible = True
End If
If Button1.Visible = False Then
Button1.Visible = True
End If
End Sub
2.the error happen when I'm trying to sort the data.
Protected Sub SortRecords(sender As Object, e As GridViewSortEventArgs)
Dim SortDir As String = String.Empty
Dim sortExpression As String = e.SortExpression
Dim dv As New DataView(GridView1.DataSource)
If dv IsNot Nothing Then
If direction = SortDirection.Ascending Then
direction = SortDirection.Descending
SortDir = "Desc"
ViewState("SortExpression") = Convert.ToString(e.SortExpression & " " & SortDir)
Else
direction = SortDirection.Ascending
SortDir = "Asc"
ViewState("SortExpression") = Convert.ToString(e.SortExpression & " " & SortDir)
End If
End If
dv.Sort = ViewState("SortExpression").ToString
GridView1.DataSource = dv
GridView1.DataBind()
end sub
The error happen on this code
dv.Sort = ViewState("SortExpression").ToString
Any help would be great. Thanks in advance
this is my aspx GridView:
<asp:GridView ID="GridView1" width="100%" runat="server"
AllowSorting="True"
OnSorting="SortRecords"
OnRowDataBound="GridView1_RowDataBound"
ItemStyle-HorizontalAlign="Center"
AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="ID" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle HorizontalAlign="center" Width="5%" />
</asp:TemplateField>
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="LOT_ID" HeaderText="Lot ID" />
<asp:BoundField DataField="PkgName" HeaderText="PIN PACKAGE NAME" />
<asp:BoundField DataField="MBTBoardNo" HeaderText="MBTBoardNo" SortExpression="MBTBoardNo" />
<asp:BoundField DataField="BTProgramName" HeaderText="BT Program Name" />
<asp:BoundField DataField="ProductRank" HeaderText="ProdRank"/>
<asp:BoundField DataField="BASEPRODUCTNAME" HeaderText="BPN" />
<asp:BoundField DataField="MCNo" HeaderText="MC No" />
<asp:BoundField DataField="QTY" HeaderText="Qty" />
<asp:BoundField DataField="CreateDate" HeaderText="Start Date" />
<asp:BoundField DataField="CheckIn" HeaderText="CheckIn" />
<asp:BoundField DataField="CheckOut" HeaderText="CheckOut" />
</Columns>
</asp:GridView>
This may be overkill butI need to explain some things.
Sql injection attacks aside for the moment you have a lot of other thing to understand first.
You are having trouble sorting because you have not Cached the retrieved data to any persistence mechanism. This Code in your sorting mechanism will always evaluate to Nothing:
Dim dv As New DataView(GridView1.DataSource)
A GridView DataSource is not persisted across postbacks unless you
use a Caching data control like SqlDataSource which manages the
cache for you.
Or you do so programmatically in one of:
ViewState(bad idea)
SessionState(not perfect)
the Application Cache(ideal)
But back to basics:
Here is an edited and annotated version of the first part of your post
I'll provide a cleaned up version following this:
Protected Sub bpn_Click(sender As Object, e As EventArgs)
' Added for clarity
Dim cs as String = ConfigurationManager.ConnectionStrings("SQLServer2005DBConnectionString").ToString()
' Try is generally not needed if you are using Using
' at least not here. Move it to the inner most Using block and
' wrap it around the actual command execution to catch sql errors
' you want to personally manage.
' Try
Using connection As New SqlConnection(cs)
connection.Open()
' String.Format() - learn to love this function
Dim sql As String = String.Format("select * from LOT WHERE PRODUCTNAME ='{0}' order by checkin asc", txtbpn.Text)
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
' This reader is not necessary as all you are doing
' is using it to determine if there is anything to do
' This is a waste of time
' You already have one open connection and
' now you are jumping to a bind operation
' that opens more.
' Generally speaking:
' open a data connection, get the data, close the connection
Using reader As SqlDataReader = cmd.ExecuteReader
' Do this here, not in both parts of the `If`
lblerror.Visible = reader.HasRows
' lblerror.Text can be initialized here or in the .aspx
' as you do nothing else with it but toggle its visibility
' Plus you can make use of a GridView's EmptyDataText property
' and get rid of the Label altogether.
lblerror.Text = "bpn not found"
If reader.HasRows Then
Me.BindBpn()
End If
' This code is not needed as it's handled by the outer Using
' connection.Dispose()
' connection.Close()
// Since this code happens in both parts of the
// IF, it only needs to happen once.
txtbpn.Text = String.Empty
TextBox2.Text = String.Empty
TextBox3.Text = String.Empty
TextBox4.Text = String.Empty
TextBox5.Text = String.Empty
// Check your original code: 2 Using requires 2 End Using
End Using
End Using
' See Try above
Catch ex As Exception
Response.Write(ex.Message)
'Why are you trying to refresh every second?
Response.AppendHeader("Refresh", "1;url=Summary.aspx")
End Try
End Sub
Here is the Revised Code without all the comments
Protected Sub bpn_Click(sender As Object, e As EventArgs)
Dim cs as String = ConfigurationManager.ConnectionStrings("SQLServer2005DBConnectionString").ToString()
Using connection As New SqlConnection(cs)
connection.Open()
Dim sql As String = String.Format("select * from LOT WHERE PRODUCTNAME ='{0}' order by checkin asc", txtbpn.Text)
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
Using sda As New SqlDataAdapter( cmd )
Try
Dim dt As New DataTable()
sda.Fill(dt)
Dim dv as New DataView(dt)
' This will persist the retrieved record set
' -- Replaced C# syntax with VB
Cache("AStringToIdentifyThisGridviewCache") = dv
GridView1.DataSource = Cache("AStringToIdentifyThisGridviewCache")
Gridview1.EmptyDataText = "bpn not found"
GridView1.DataBind()
GridView1.Visible = (GridView1.Rows.Count > 0)
txtbpn.Text = String.Empty
TextBox2.Text = String.Empty
TextBox3.Text = String.Empty
TextBox4.Text = String.Empty
TextBox5.Text = String.Empty
Catch ex As Exception
Gridview1.EmptyDataText = ex.Message
End Try
End Using
End Using
End Sub
One more thing, your data is going to be retrieved from the database and will overwrite the Cache and rebind to the GridView every time you hit the button.
Typically you want to retrieve the data once and then work with the Cached dataset until the data is modified in some way that it requires another database hit.
Programmatic data retrieval and binding is certainly useful, but I find I rarely need to use it. You may be under requirements for this project but for GridView operations, it's hard to beat the provided DataSource Controls.
Hope this helps.
Happy Coding.
Sorting Code lifted from MSDN Sample for GridView Sorting
Protected Sub SortRecords(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
'Retrieve the table from the session object.
Dim dv As DataView = TryCast(Cache("AStringToIdentifyThisGridviewCache"), DataView)
If dv IsNot Nothing Then
'Sort the data.
dv.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
GridView1.DataSource = Cache("AStringToIdentifyThisGridviewCache")
GridView1.DataBind()
End If
End Sub
Private Function GetSortDirection(ByVal column As String) As String
' By default, set the sort direction to ascending.
Dim sortDirection = "ASC"
' Retrieve the last column that was sorted.
Dim sortExpression = TryCast(ViewState("SortExpression"), String)
If sortExpression IsNot Nothing Then
' Check if the same column is being sorted.
' Otherwise, the default value can be returned.
If sortExpression = column Then
Dim lastDirection = TryCast(ViewState("SortDirection"), String)
If lastDirection IsNot Nothing _
AndAlso lastDirection = "ASC" Then
sortDirection = "DESC"
End If
End If
End If
' Save new values in ViewState.
ViewState("SortDirection") = sortDirection
ViewState("SortExpression") = column
Return sortDirection
End Function
I'm trying to insert records into my Access database using the following code:
<script runat="server">
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbReader As OleDbDataReader
Dim sqlString As String
Sub page_load()
Try
txtFName.Text = ""
txtLName.Text = ""
dbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" & Server.MapPath("MyDatabase.accdb"))
dbConnection.Open()
sqlString = "SELECT * FROM table1 ORDER BY ID"
dbCommand = New OleDbCommand(sqlString, dbConnection)
dbReader = dbCommand.ExecuteReader()
While dbReader.Read()
Dim lblName As Label = New Label()
lblName.ID = dbReader("ID")
lblName.Text = "<b>Name: </b>" & dbReader("F_Name") & " " & dbReader("L_Name") & "<br/><br/>"
lblName.EnableViewState = False
nameArea.Controls.Add(lblName)
End While
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
Sub addToDatabase()
Try
dbConnection.Open()
sqlString = "INSERT INTO table1 (F_Name,L_Name) VALUES (#FName, #LName)"
dbCommand.CommandText = sqlString
dbCommand.Parameters.AddWithValue("#FName", txtFName.Text)
dbCommand.Parameters.AddWithValue("#LName", txtLName.Text)
dbCommand.ExecuteNonQuery()
Finally
dbConnection.Close()
End Try
End Sub
</script>
In my asp code below, I have two TextBoxes to hold first name and last name, as well as a button that will call addToDatabase when clicked, and a placeholder to display each record pulled from the database:
<asp:TextBox ID="txtFName" runat="server" />
<asp:TextBox ID="txtLName" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit" OnClick="addToDatabase" runat="server" />
<br />
<asp:PlaceHolder ID="nameArea" runat="server" />
My access database contains a table named table1, with an ID, F_Name and L_Name field, with their DataTypes being AutoNumber, Text and Text respectively.
My problem is when I click btnSubmit, it adds blank records into my database for F_Name and L_Name instead of what was in the TextBoxes, and continues to add blank records on every browser refresh.
What is going on?
Remove the following lines from your page_load method.
txtFName.Text = ""
txtLName.Text = ""
Add the following at the end of the addToDatabase method. This will then show you the new names in the page without needing a call to the database.
Dim lblName As Label = New Label()
lblName.ID = dbReader("ID")
lblName.Text = "<b>Name: </b>" & txtFName.Text & " " & txtLName.Text & "<br/><br/>"
lblName.EnableViewState = False
nameArea.Controls.Add(lblName)
I moved my code around and added a new Sub that will get names, then called that method on initial page_load and after calling addToDatabase. I kept everything else in the asp below the same.
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbReader As OleDbDataReader
Dim sqlString As String
Sub page_load()
dbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" & Server.MapPath("MyDatabase.accdb"))
dbCommand = New OleDbCommand("", dbConnection)
If Not Page.IsPostBack Then
showNames()
End If
End Sub
Sub showNames()
Try
dbConnection.Open()
sqlString = "SELECT * FROM table1 ORDER BY ID"
dbCommand.CommandText = sqlString
dbReader = dbCommand.ExecuteReader()
While dbReader.Read()
Dim lblName As Label = New Label()
lblName.ID = dbReader("ID")
lblName.Text = "<b>Name: </b>" & dbReader("F_Name") & " " & dbReader("L_Name") & "<br/>"
lblEntry.EnableViewState = False
nameArea.Controls.Add(lblName)
End While
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
Sub addToDatabase(src As Object, args as EventArgs)
Try
dbConnection.Open()
sqlString = "INSERT INTO table1 (F_Name,L_Name) VALUES (#FName, #LName)"
dbCommand.CommandText = sqlString
dbCommand.Parameters.AddWithValue("#FName", txtFName.Text)
dbCommand.Parameters.AddWithValue("#LName", txtLName.Text)
dbCommand.ExecuteNonQuery()
Finally
dbConnection.Close()
End Try
showNames()
End Sub
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 have a search engine that will use a webservice to search through my database to find 3 specific things. I don't even know if it will work like this, but I have a dropdown list on my main page to select Product, Feature, Description. From what the user selects, the webservice should then go to an if statement to use the correct SELECT statement and find results for the search.
Will someone help me figure out how to fix what I've written to make it work? Please don't be too critical, I don't have a lot of experience. I have also been researching SQL Injection because I have a lot of code that is vulnerable so keep that in mind when you look at my code.
I can't get the blue squiggly lines to go away that are underneath the DropdownList1.Value instances on the WebService page.
WebService:
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()
Dim Feature As String = DropDownList1.Value
Dim Description As String = DropDownList1.Value
Dim Product As String = DropDownList1.Value
If Feature Then
Dim FeatureSql As String = "Select FeatureTitle FROM Feature WHERE FeatureTitle LIKE " + " " '%" + prefixText + "'"
Dim sqlConn As New SqlConnection("Server=off-db1;uid=productsDB_admin;pwd=******;database=Products")
sqlConn.Open()
Dim myCommand As New SqlCommand(FeatureSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "FeatureSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("FeatureTitle").ToString(), i)
i += 1
Next
Return items
End If
If Description Then
Dim MarketingSql As String = "Select MarketingType, MarketingData FROM Marketing WHERE MarketingType = '2' AND MarketingData LIKE " + " " '%" + prefixText + "'"
Dim sqlConn As New SqlConnection("Server=off-db1;uid=productsDB_admin;pwd=*****;database=Products")
sqlConn.Open()
Dim myCommand As New SqlCommand(MarketingSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "DescriptionSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("MarketingType").ToString(), i)
items.SetValue(dr("MarketingData").ToString(), i)
i += 1
Next
Return items
End If
If Product Then
Dim ProductSql As String = "Select ProductName FROM Product WHERE ProductName LIKE " + " " '%" + prefixText + "'"
Dim sqlConn As New SqlConnection("Server=off-db1;uid=productsDB_admin;pwd=*****;database=Products")
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "ProductSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("ProductName").ToString(), i)
i += 1
Next
Return items
End If
End Function
End Class
Default.aspx page - Here I need the dropdownlist to tie to the database somehow.
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
Search by:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Product</asp:ListItem>
<asp:ListItem>Feature</asp:ListItem>
<asp:ListItem>Description</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="Search" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="3" CompletionSetCount="120" EnableCaching="true">
</asp:AutoCompleteExtender>
I deleted the dropdown and tested the code of one of the select statements to make sure that it was working correctly. Everyone was right when they said that the dropdown would not work with the webservice the way I wanted it to. :(
Here is what I have now:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="FeatureSearch.asmx" />
</Services>
</asp:ScriptManager>
<asp:TextBox ID="Search" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/FeatureSearch.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="2" CompletionSetCount="120" EnableCaching="true">
</asp:AutoCompleteExtender>
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select ProductName FROM Product WHERE ProductName LIKE '" & prefixText & "%'"
Dim sqlConn As New SqlConnection
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "ProductSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
Dim id As String = dr("ProductID").ToString()
Dim name As String = dr("ProductName").ToString()
Dim item As String = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(name, id)
items.SetValue(item, i)
Next
Return items
End Function
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()