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
Related
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."
I want to perform the following function but I am having problems, no errors appear in my code but the table does not update when clicked.
When the user logs in and are redirected to the user.aspx page on a session a grid appears with their own medication from a link table - (holding medicineId from medicine and patientId from patient).
When the user selects their medicine from the gridview and chooses a pharmacy from the pharmacy drop down then clicks the btnconfirm button it should insert into the order_pres table - I have included a picture with steps of this.
I will include both my code from user.aspx and user.aspx.vb to provide understanding of the page as a whole and the function:
User.aspx
'Grid to select medicine from:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Select" CommandName="UpdateMedicine" CommandArgument='<%# Eval("MedicineId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Purpose" HeaderText="Purpose" />
<asp:BoundField DataField="Instrcutions" HeaderText="Instructions" />
</Columns>
</asp:GridView>
<br />
' Holds the Pharmacy name from pharmacy
<asp:SqlDataSource ID="SqlPharm" runat="server" ConnectionString="<%$ ConnectionStrings:SurgeryConnectionString %>" SelectCommand="SELECT DISTINCT Pharmname FROM Pharmacy "></asp:SqlDataSource>
<br />
' shows the pharmay name from pharmacy (there are 3 pharmacies in table)
<asp:DropDownList ID="DropPharm" runat="server" DataSourceID="SqlPharm" DataTextField="Pharmname" DataValueField="Pharmname"></asp:DropDownList>
'button to perform the insert query after selections have been made
User.aspx.vb
Imports System.Data.SqlClient
Imports System.Data
Partial Class Pages_user
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'shows grid when on session with the user that loggs in
If Not IsPostBack Then
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Integrated Security=True;Connect Timeout=30")
Dim cmdstring As String = "SELECT md.MedicineId, md.Name, md.Purpose, md.Instrcutions " +
"FROM Patient pt INNER JOIN prescription pr ON pt.PatientId = pr.PatientId " +
"INNER JOIN medicine md ON md.MedicineId = pr.MedicineId Where pt.PatientId = #PatientId"
Dim dt As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmdstring, conn)
da.SelectCommand.Parameters.Add("#PatientId", System.Data.SqlDbType.Int).Value = CInt(Session("PatientId").ToString())
conn.Open()
da.Fill(dt)
conn.Close()
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
'select command for grid
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
lbldrop.Text = e.CommandArgument.ToString()
If e.CommandName = "UpdateMedicine" Then
Session("MedicineID") = Integer.Parse(e.CommandArgument.ToString())
End If
End Sub
Protected Sub btnconfirm_Click(sender As Object, e As EventArgs) Handles btnconfirm.Click
Dim PatientId As Integer = Session("PatientId").ToString
Dim PharmacyId As Integer = Session("PharmacyId").ToString
Dim DateOrdered As Date
Dim MedicineId As Integer = Session("MedicineID")
' Get DoctorId from the patient table
Dim DoctorId As String = "SELECT DoctorId FROM Patient "
'add PatientId, DoctorId, MedicineId, PharmacyId and date ordered to Order_pres table
Dim query As String = String.Empty
query &= "INSERT INTO Order_pres (PatientId, PharmacyId, "
query &= " DoctorId, [Date Ordered]) "
query &= "VALUES (#PatientId,#MedicineId, #PharmacyId, #DoctorId, #DateOrdered)"
Dim sqlCs As String = ConfigurationManager.ConnectionStrings("SurgeryConnectionString").ConnectionString
Using conn As New SqlConnection(sqlCs),
comm As New SqlCommand(query, conn)
With comm.Parameters
.Add("#PatientId", SqlDbType.Int).Value = Session("PatientId").ToString
.Add("#DoctorId", SqlDbType.Int).Value = Session("DoctorId").ToString
.Add("#MedicineId", SqlDbType.Int).Value = Session("Medicine").ToString
.Add("#DateOrdered", SqlDbType.DateTime).Value = DateTime.Parse(DateOrdered)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
lblconfirm.Text() = "Order Placed"
Catch ex As SqlException
lblnoconfirm.Text() = "Order not placed"
End Try
End Using
The sessions in the log in page:
Dim reader = cmd.ExecuteReader()
While reader.Read()
Session("PatientId") = CInt(reader.Item("PatientId"))
Session("Username") = CStr(reader.Item("Username"))
Session("DoctorId") = CStr(reader.Item("DoctorId"))
found = CInt(reader.Item("PatientId"))
End While
What the user page currently looks like and the steps:
I am sorry for the amount of information I have provided but I thought it was essential to include for understanding of the question, hopefully someone else may spot where I am going wrong
You are writing your query with 5 parameters placeholders, but you add only 4 parameters and try to update only 4 fields.
This should trigger an exception about a parameter missing.
But your code hides this problem swallowing the exception and just writing a message to your user (and to you as programmer that has no clue on what is going wrong).
So supposing that you want to update all 5 fields with 5 parameters your query could be something like this
Protected Sub btnconfirm_Click(sender As Object, e As EventArgs) Handles btnconfirm.Click
Dim PatientId As Integer = Session("PatientId").ToString
Dim PharmacyId As Integer = Session("PharmacyId").ToString
Dim DateOrdered As Date ' ??? where do you initialize this value ????
Dim MedicineId As Integer = Session("MedicineID")
Dim DoctorId As String
' Get DoctorId from the patient table
' here put the code that initializes the DoctorID variable
' something like ... DoctorId = GetDoctorId() ...
Dim query As String = String.Empty
query &= "INSERT INTO Order_pres (PatientId, MedicineID, PharmacyId,"
query &= " DoctorId, [Date Ordered]) "
query &= "VALUES (#PatientId,#MedicineId, #PharmacyId, #DoctorId, #DateOrdered)"
Dim sqlCs As String = ConfigurationManager.ConnectionStrings("SurgeryConnectionString").ConnectionString
Using conn As New SqlConnection(sqlCs),
comm As New SqlCommand(query, conn)
With comm.Parameters
.Add("#PatientId", SqlDbType.Int).Value = patientID
.Add("#PharmacyId", SqlDbType.Int).Value = PharmacyID
.Add("#DoctorId", SqlDbType.Int).Value = DoctorId
.Add("#MedicineId", SqlDbType.Int).Value = MedicineID
.Add("#DateOrdered", SqlDbType.DateTime).Value = DateTime.Parse(DateOrdered)
End With
Try
conn.Open()
Dim rowInserted = comm.ExecuteNonQuery()
if rowInserted = 1 Then
lblconfirm.Text = "Order Placed"
else
lblnoconfirm.Text = "Order not placed"
End If
Catch ex As SqlException
lblnoconfirm.Text = "Unexpectd error: " & ex.Message
End Try
End Using
End Sub
Note that all of your fields (except the Date Ordered) are of type integer, so when using AddWithValue don't convert these values to a string. This force the database engine to convert them back to an integer and this is a possible cause of problems (better use the Add method for the parameters collection specifying the exact type of the parameter)
Finally, the ExecuteNonQuery returns the number of rows inserted (or deleted or updated) by the query. So a return different of 0 a clear signal that your query has not worked)
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
We would like our administrators to select a user from the dropdownlist and have the role or roles associated with that user be displayed in a checkbox.
When I attempt to run the code below, I get
Conversion failed when converting the varchar value 'John Mayer' to data type int
Any ideas how to resolve this?
Below is code I am using.
'//Markup
<p>
<b>Select a User:</b>
<asp:DropDownList ID="UserList" runat="server" AutoPostBack="True"
DataTextField="UserName" DataValueField="LoginId" OnSelectedIndexChanged="UserList_SelectedIndexChanged">
</asp:DropDownList>
</p>
<p>
<div class="roleList">
<asp:CheckBoxList ID="RoleList" runat="server">
</asp:CheckBoxList>
</div>
'//CodeBehind
Public Sub PopulateUserList()
Dim cmd As New SqlCommand("Select LoginId,UserName from tblLogin", New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString))
cmd.Connection.Open()
Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()
UserList.DataSource = ddlValues
UserList.DataValueField = "LoginId"
UserList.DataTextField = "UserName"
UserList.DataBind()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub
Protected Sub UserList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim conn As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim ds As DataSet = New DataSet()
Dim sql As String = "select UserRoles from tblLogin where userName = " + UserList.SelectedValue
Dim AD As New SqlDataAdapter(sql, conn)
AD.Fill(ds, "table")
RoleList.DataSource = ds.Tables(0)
RoleList.DataTextField = "UserRoles"
RoleList.DataValueField = "LoginId"
RoleList.DataBind()
End Sub
Thank you
Probably you need to retrieve also the LoginID from the table and not only the UserRoles
Protected Sub UserList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim conn As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim ds As DataSet = New DataSet()
Dim sql As String = "select LoginId, UserRoles from tblLogin " +
"where userName = #uname"
Dim AD As New SqlDataAdapter(sql, conn)
AD.SelectCommand.Parameters.AddWithValue("#uname", UserList.SelectedItem.Text)
AD.Fill(ds, "table")
RoleList.DataSource = ds.Tables(0)
RoleList.DataTextField = "UserRoles"
RoleList.DataValueField = "LoginId"
RoleList.DataBind()
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()