How to add the textbox name as parameter in a sub - sql

I have created a button to add the fields in a a textbox and I wanted to pass the textbox name as parameter in a sub,which inturn inserts into the database..How can i do it..pls find my code for reference below in vb.net
The code for inserting the values in database
Sub Add_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim addedButton As Button = sender
Dim sqlcmd As SqlCommand
Dim insertdata As String
addedButton.Text = "Added"
adduser = True
addedButton.Enabled = True
If (cname.Value = " " Or cid.Value = " " Or cadd.Value = " " Or cph.Value = " " Or fax.Value = " " Or cmail.Value = " ") Then
Message.InnerHtml = "ERROR: Null values not allowed for " _
& "Client ID, Name"
Message.Style("color") = "red"
BindGrid()
Else
Message.InnerHtml = "<b>Client Record has been added</b><br/>"
End If
insertdata = "INSERT INTO dbo.ClientInfo([Client Name],[Client ID],[Client Address],[Client Telephone No],[Client Fax No],[Client E-mail]) values("
insertdata = insertdata + " ' " + cname.Value + " '," + cid.Value + ",' " + cadd.Value + " '," + cph.Value + "," + fax.Value + "," + cmail.Value
sqlcmd = New SqlCommand(insertdata, sqlcon)
Try
sqlcmd.Connection.Open()
Dim addcount As Integer = sqlcmd.ExecuteNonQuery()
If addcount > 0 Then
Message.InnerHtml = "Record successfully Added"
Else
Message.InnerHtml = "Record not added"
End If
Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists with " _
& "the same primary key"
End If
Finally
sqlcmd.Connection.Close()
BindGrid()
End Try
End Sub
<asp:Button id="Button1"
Text="Add data"
OnClick="Add_Click"
runat="server"/><br />
Name:<input type ="text" id="cname" name="" value="" runat="server"/><br />
ID: <input type = "text" id="cid" name="txtclientid" value="" runat="server"/><br />
Address:<input type="text" id="cadd" name="txtclientadd" value="" runat="server"/><br />
Phone No:<input type="text" id="cph" name="txtno" value="" runat="server" /><br />
Fax No:<input type="text" id="fax" name="faxno" value="" runat="server"/><br />
E-mail:<input type="text" id="cmail" name="mail" value="" runat="server"/><br />
<input type="reset" name="reset" value="Clear" /><br />

Not exactly what you asked for, but closer to what you should be doing:
Public Sub InsertClientInfo(ByVal ClientName As String, ByVal ClientID As Integer, ByVal ClientAddress As String, ByVal ClientPhone As String, ByVal ClientFax As String, ByVal ClientEmail As String)
Dim sql As String = _
"INSERT INTO ClientInfo (" & _
"[Client Name],[Client ID],[Client Address],[Client Telephone No],[Client Fax No],[Client E-mail]" & _
") VALUES (" & _
"#ClientName, #ClientID, #ClientAddress, #ClientPhone, #ClientFax, #ClientEmail)"
Using cn As New SqlConnection("connection string"), _
cmd As New SqlCommand(sql, cn)
'I had to guess at the column types and lengths here. Adjust accordingly
cmd.Parameters.Add("#ClientName", SqlDbType.NVarChar, 50).Value = ClientName
cmd.Parameters.Add("#ClientID", SqlDbType.Int).Value = ClientID
cmd.Parameters.Add("#ClientAddress", SqlDbType.NVarChar, 200).Value = ClientAddress
cmd.Parameters.Add("#ClientPhone", SqlDbType.NVarChar, 16).Value = ClientPhone
cmd.Parameters.Add("#ClientFax", SqlDbType.NVarChar, 16).Value = ClientFax
cmd.Parameters.Add("#ClientEmail", SqlDbType.NVarChar, 50).Value = ClientEmail
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Note that I had to guess at data types and sizes. You need to fix that to make your actual table definitions. Call it like this:
InsertClientInfo(textname.Text, Convert.ToInt32(textclientid.Text), txtclientadd.Text, txtno.Text, faxno.Text, mail.Text)

To pass the TEXTBOX name to any sub do as follows,
Sub SomeSubName(ThisTextboxName as string)
'your code here
End Sub
or to a function
Function SomeFunctionName(ThisTextBoxName as String) As Boolean
'your code here
End Function
Where...
SomeSubName and SomeFunctionName are the names of your sub or function
ThisTextBoxName is the variable name of the STRING data which is the actual textbox name
So if your textbox is named txtPhone Then you would pass it as....
SomeSubName(txtPhone.Name)
or
Dim Test as Boolean
Test = SomeFunctionName(txtPhone.Name)

Related

in vb.net error Command text was not set for the command object

I have a program in vb.net where I need data inserted into the database. When I run this code I get an error:
Command text was not set for the command object
Here is the code I have:
Private Sub InsertRelease(strRelease As String, rowInserted As Boolean)
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim objType As String
Dim strUsername, strPassword, strTable, strDatabase, strDsn, strSystem, strNewSql, sqlStr As String
Dim intRecsAffected As Integer
Dim boolRowInserted As Boolean
strDsn = ComboBox1.Text
strSystem = txtSystem.Text
strUsername = txtUser.Text
strPassword = txtPassword.Text
If con.State <> 1 And strUsername <> "" And strPassword <> "" Then
con.Open("{iSeries As ODBC Driver};System=" + strSystem + ";Dsn=" + strDsn + "; Uid=" + strUsername + "; Pwd=" + strPassword + ";")
Else
MessageBox.Show("Please enter the correct UserName And Password")
txtUser.Focus()
con = Nothing
End If
sqlStr = "insert into jobscopedb.ppusrfs (search_key_uf,DATA_ITEM_UF, NUMERIC_VALUE_UF) values (strRelease,'81 AB',0);"
strNewSql = ""
con.Execute(strNewSql, intRecsAffected)
con.Close()
con = Nothing
boolRowInserted = (intRecsAffected > 0)
If (boolRowInserted) Then
MessageBox.Show("Release " + strRelease + " added")
Else
MessageBox.Show("Release " + strRelease + "not added")
End If
Exit Sub
errH:
MsgBox(Err.Description)
con = Nothing
End Sub
The following demonstrates what your code might look like using ADO.net.
Pass the connection string directly to the constructor of the connection and pass the command text and connection to the constructor of the command. Open the connection and execute the command. ExecuteNonQuery returns rows affected.
Always use parameters to avoid sql injection.
Private Sub InsertRelease(strRelease As String)
Dim intRecsAffected As Integer
Dim strDsn = ComboBox1.Text
Dim strSystem = txtSystem.Text
Dim strUsername = txtUser.Text
Dim strPassword = txtPassword.Text
'Validate Input
If strUsername = "" OrElse strPassword = "" Then
MessageBox.Show("Please enter the correct UserName And Password")
txtUser.Focus()
Exit Sub
End If
Using con As New OdbcConnection($"{{iSeries As ODBC Driver}};System={strSystem};Dsn={strDsn}; Uid={strUsername}; Pwd={strPassword};"),
cmd As New OdbcCommand("insert into jobscopedb.ppusrfs (search_key_uf, DATA_ITEM_UF, NUMERIC_VALUE_UF) values (#Release,'81 AB',0);", con)
cmd.Parameters.Add("#Release", OdbcType.VarChar).Value = strRelease
con.Open()
intRecsAffected = cmd.ExecuteNonQuery
End Using 'Closes and disposes the connection and command even it there is an error
If intRecsAffected = 1 Then
MessageBox.Show("Release " + strRelease + " added")
Else
MessageBox.Show("Release " + strRelease + "not added")
End If
End Sub

Input string was not in a correct format. Gridview

I am in the middle doing my school work however i having some error with my code but i run this similar code in my other file and there is no issue. Hope you guys can help me. It's about getting multi datakeyname
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Width="100%" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging2" PageSize="3" CssClass="Grid" DataKeyNames="id, tripidtaking, reqid" >
<Columns>
<asp:BoundField DataField="fname" />
<asp:BoundField DataField="reqid" HeaderText="Req ID" />
<asp:BoundField DataField="tripidtaking" HeaderText="trip ID" />
<asp:BoundField DataField="id" HeaderText="trip ID" />
<asp:BoundField DataField="startptname" HeaderText="Origin" />
<asp:BoundField DataField="endptname" HeaderText="Destination" />
<asp:BoundField DataField="givendate" HeaderText="Date" />
<asp:BoundField DataField="starttime" HeaderText="Agreed Time" />
<asp:BoundField DataField="numperson" HeaderText="NoOfPpl" />
<asp:BoundField DataField="Recurring" HeaderText="Whether Recurring" />
<asp:BoundField DataField="day" HeaderText="Selected Day" />
<asp:BoundField DataField="usertype" HeaderText="Type" />
<asp:BoundField DataField="Cfname" HeaderText="Driver Name" />
<asp:BoundField DataField="cid" HeaderText="Driver ID" />
<asp:BoundField DataField="" HeaderText="" />
<asp:BoundField DataField="" HeaderText="" />
</Columns>
</asp:GridView>
Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
Dim row As GridViewRow = e.Row
If row.RowType = DataControlRowType.DataRow Then
Dim lb2 As New LinkButton()
lb2.ID = "lbCancel"
lb2.Text = "Cancel"
lb2.CommandName = "CancelRow"
lb2.CommandArgument = DataBinder.Eval(row.DataItem, "ID")
row.Cells(14).Controls.Add(lb2)
If row.Cells(13).Text = reqid Then
Dim lb As New LinkButton()
lb.ID = "lbEnd"
lb.Text = "End"
lb.CommandName = "EndRow"
lb.CommandArgument = DataBinder.Eval(row.DataItem, "tripidtaking") + "," + DataBinder.Eval(row.DataItem, "reqid")
row.Cells(15).Controls.Add(lb)
End If
End If
End Sub
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand
Dim reqid As String = Session("reqid")
Dim arguments As String() = e.CommandArgument.ToString().Split(New Char() {","})
If (e.CommandName = "CancelRow") Then
Dim ID As String = arguments(0)
myconnection.Open()
Using mycommand As SqlCommand = myconnection.CreateCommand
mycommand.CommandText = "delete from ongoing_trips where id=" + ID
mycommand.ExecuteNonQuery()
End Using
myconnection.Close()
Response.Redirect("mytrip.aspx")
'Response.Write("<script language='javascript'> alert(" + ID + "); </script>")
ElseIf (e.CommandName = "EndRow") Then
Dim rid As String = arguments(2)
Dim tripIDtaking As String = arguments(1)
Dim uid As String = ""
Dim uname As String = ""
Dim fname As String = ""
Dim lname As String = ""
Dim tid As String = ""
Dim status As String = ""
Dim stptname As String = ""
Dim edptname As String = ""
Dim gdate As String = ""
Dim stime As String = ""
Dim etime As String = ""
Dim nop As String = ""
Dim uty As String = ""
Dim cfname As String = ""
Dim cid As String = ""
Dim recur As Char = ""
Using con As New SqlConnection(connString)
Using cmd As New SqlCommand("SELECT * FROM ongoing_trips inner JOIN accounts ON ongoing_trips.reqid=accounts.userid inner join trips on ongoing_trips.tripidtaking=trips.tripid where (ongoing_trips.status='ACTIVE' AND ongoing_trips.reqid='" + rid + "') and ongoing_trips.tripidtaking='" + tripIDtaking + "'")
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
uid = Convert.ToString(reader("userid").ToString())
uname = Convert.ToString(reader("uname").ToString())
fname = Convert.ToString(reader("fname").ToString())
lname = Convert.ToString(reader("lname").ToString())
tid = Convert.ToString(reader("tripid").ToString())
stptname = Convert.ToString(reader("startptname").ToString())
edptname = Convert.ToString(reader("endptname").ToString())
gdate = Convert.ToString(reader("givendate").ToString())
stime = Convert.ToString(reader("starttime").ToString())
etime = Convert.ToString(reader("endtime").ToString())
nop = Convert.ToString(reader("numperson").ToString())
uty = Convert.ToString(reader("usertype").ToString())
recur = Convert.ToString(reader("recurring").ToString())
cfname = Convert.ToString(reader("cfname").ToString())
cid = Convert.ToString(reader("cid").ToString())
End While
con.Close()
End Using
End Using
If recur = "Y" Then
Response.Write("<script language='javascript'> alert('y'); </script>")
ElseIf recur = "N" Then
Using con2 As New SqlConnection(connString2)
con2.Open()
Using mycommand As SqlCommand = con2.CreateCommand
mycommand.CommandText = "insert into trips_history values (#userid, #uname, #fname, #lname, #tripid, 'COMPLETED', #startptname, #endptname, #givendate, #starttime, #endtime, #numperson, #usertype, SYSDATETIME(), #cfname, #cid)"
mycommand.Parameters.AddWithValue("#userid", uid)
mycommand.Parameters.AddWithValue("#uname", uname)
mycommand.Parameters.AddWithValue("#fname", fname)
mycommand.Parameters.AddWithValue("#lname", lname)
mycommand.Parameters.AddWithValue("#tripid", tid)
mycommand.Parameters.AddWithValue("#startptname", stptname)
mycommand.Parameters.AddWithValue("#endptname", edptname)
mycommand.Parameters.AddWithValue("#givendate", gdate)
mycommand.Parameters.AddWithValue("#starttime", stime)
mycommand.Parameters.AddWithValue("#endtime", etime)
mycommand.Parameters.AddWithValue("#numperson", nop)
mycommand.Parameters.AddWithValue("#usertype", uty)
mycommand.Parameters.AddWithValue("#cfname", cfname)
mycommand.Parameters.AddWithValue("#cid", cid)
mycommand.ExecuteNonQuery()
End Using
con2.Close()
End Using
myconnection.Open()
Using mycommand As SqlCommand = myconnection.CreateCommand
mycommand.CommandText = "delete from ongoing_trips where tripidtaking=" + tripIDtaking
mycommand.ExecuteNonQuery()
End Using
myconnection.Close()
Response.Redirect("myhistory.aspx")
End If
End If
End Sub
I not sure why this error happen upon loading of the page i got this error

Error when updating SQLite database using VB.Net

Trying to get this code to work so that it will update my SQLite database. Keep getting an error saying that an end of statement is expected error BC30205. I cannot see what i am missing! This is my first ever attempt at an update statement in SQL so i may have missed something obvious! I have marked the line of code i am having the error with with an arrow!
Public Partial Class Change_Password
Public Sub New()
' The Me.InitializeComponent call is required for Windows Forms designer support.
Me.InitializeComponent()
'
' TODO : Add constructor code after InitializeComponents
'
End Sub
Dim SQLconnect As New System.Data.SQLite.SQLiteConnection()
Dim SQLcommand As System.Data.SQLite.SQLiteCommand
Dim SQLreader As System.Data.SQLite.SQLiteDataReader
Dim Password1 As String = ""
Dim Password2 As String = ""
Public Class Password
Public shared usernamechange As String = ""
End Class
Sub Cmd_NextClick(sender As Object, e As EventArgs)
If Trim(txt_Password_Box.Text) = "" Then
MsgBox("Please enter a password")
Else
Password1 = txt_Password_Box.Text
txt_Password_Box.Text = ""
txt_Password_Box.Focus
lbl_Instruction.Text = "Please re-enter the exact same password!"
cmd_Submit.Visible = True
cmd_Next.Visible = False
Me.AcceptButton = cmd_Submit
End If
End Sub
Sub Change_PasswordLoad(sender As Object, e As EventArgs)
cmd_Submit.Visible = False
Me.AcceptButton = cmd_Next
SQLconnect.ConnectionString = "Data Source=KCD.s3db;"
SQLconnect.Open()
End Sub
Sub Cmd_SubmitClick(sender As Object, e As EventArgs)
If Trim(txt_Password_Box.Text) = "" Then
MsgBox("Please enter the password again")
Exit Sub
Else
Password2 = txt_Password_Box.Text
txt_Password_Box.Text = ""
End If
If Password1 = Password2 Then
SQLcommand = SQLconnect.CreateCommand
------> SQLcommand.CommandText = "UPDATE Staff SET Password = '" & password1 & "' WHERE '" Username = "' & password.usernamechange & '"""
SQLcommand.Dispose()
MsgBox("Your password has been changed",vbInformation,"Password Changed")
Me.Close
Else
MsgBox("Passwords do not match. Please try again.")
txt_Password_Box.Focus
cmd_Submit.Visible = False
cmd_Next.Visible = True
Password1 = ""
Password2 = ""
lbl_Instruction.Text = "Please enter a new password!"
Me.AcceptButton = cmd_Next
End If
End Sub
End Class
Hope someone can help me! Thanks
This line doesn't seem right. Change
SQLcommand.CommandText = "UPDATE Staff SET Password = '" & password1 & "' WHERE '" Username = "' & password.usernamechange & '"""
to
SQLcommand.CommandText = "UPDATE Staff SET Password = '" & password1 & "' WHERE Username = '" & password.usernamechange & "'"
BTW, concatenating strings like that leads to being vulnerable to SQL Injection.

Proper way to bind SQL NULL to ASP.NET Control?

I have an ASP.NET control that I have bound to a SQL result:
<asp:GridView ID="EmployeeSearchResults" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# (EmployeeSearchStatus(Eval("SeparationDate"),Eval("PositionTitle"),Eval("EffectiveDate"))) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My EmployeeSearchStatus function is very basic, testing the values passed in for NULL, and creating a string to display:
Public Function EmployeeSearchStatus(ByVal SeparationDate As Object, ByVal PositionTitle As Object, ByVal EffectiveDate As Object) As String
Dim ReturnString As String = ""
If IsDBNull(SeparationDate) Then
ReturnString = "Currently Employed as "
Else
ReturnString = "Last Employed as "
End If
ReturnString += PositionTitle
If IsDBNull(SeparationDate) Then
ReturnString += " (effective " + EffectiveDate + ")."
Else
ReturnString += " (separated on " + SeparationDate + ")."
End If
Return ReturnString
End Function
Is this the proper way to handle NULL values coming back from SQL to an ASP.NET control? Is there a better technique?
Thanks,
Russell
Your code looks fine, although you could possibly simplify it a bit if you wanted:
Public Function EmployeeSearchStatus(ByVal SeparationDate As Object, ByVal PositionTitle As Object, ByVal EffectiveDate As Object) As String
If IsDBNull(SeparationDate) Then
Return "Currently Employed as " + PositionTitle + " (effective " + EffectiveDate + ")."
Else
Return "Last Employed as " + PositionTitle + " (separated on " + SeparationDate + ")."
End If
End Function
The code does assume, however, that PositionTitle and EffectiveDate will never be null. If this is not enforced in the database, you could add some checks to the code to deal with these situations.

How to troubleshoot "Object cannot be cast from DBNull to other types."

how can I troubleshoot "Object cannot be cast from DBNull to other types."?
I am using a combobox, to retrieve the price and discount price of the service, If I select an item in combobox3 once, error will not occur, but if I select a item again in combobox3, "Object cannot be cast from DBNull to other types." will occur..
here is my code
Private Sub ComboBox3_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox3.SelectedIndexChanged
Dim ds As New DataSet
ds = getPrice(arr(ComboBox2.SelectedIndex), ComboBox3.Text)
If ds.Tables("getPrice").Rows.Count > 0 Then
For i As Integer = 0 To ds.Tables("getPrice").Rows.Count - 1
TextBox1.Text = Convert.ToDecimal(ds.Tables("getPrice").Rows(i).Item(0))
TextBox2.Text = Convert.ToDecimal(ds.Tables("getPrice").Rows(i).Item(1))
Next
End If
End Sub
this is my query
Public Function getPrice(ByVal serviceId As String, ByVal breedSize As String)
If breedSize = "Small Breed" Then
sqlStr = "Select price_small_breed, discount_small_breed From tblServicePrice Where service_id = " + serviceId + ""
ElseIf breedSize = "Medium Breed" Then
sqlStr = "Select price_medium_breed, discount_medium_breed From tblServicePrice Where service_id = " + serviceId + ""
ElseIf breedSize = "Big Breed" Then
sqlStr = "Select price_big_breed, discount_big_breed From tblServicePrice Where service_id = " + serviceId + ""
End If
ds.Clear()
da = New OleDbDataAdapter(sqlStr, con.ConnectionString)
da.Fill(ds, "getPrice")
Return ds
End Function
here is the image
what could be the caused of having this problem?
TextBox1.Text = If(ds.Tables("getPrice").Rows(i).Item(0) Is DBNull.Value, "", Convert.ToDecimal(ds.Tables("getPrice").Rows(i).Item(0)).ToString())
TextBox2.Text = If(ds.Tables("getPrice").Rows(i).Item(0) Is DBNull.Value, "", Convert.ToDecimal(ds.Tables("getPrice").Rows(i).Item(1)).ToString())
If you run the specific query statement that was executed in GetPrice against the database, you will see that at least one of the rows has a null value at the ordinal position you are reading.
It is likely that serviceID (note the caps) is not the value you are assuming it is.
What do want to happen if there is a NULL value in the database? If it would be acceptable to use some value instead, e.g. zero, you could modify the query like
sqlStr = "Select COALESCE(price_small_breed, 0), COALESCE(discount_small_breed, 0) From tblServicePrice Where service_id = " & serviceId & ""
my answer is this.. I declare new dataset, I do not used the dataset from the top of my code
Public Function getPrice(ByVal serviceId As String, ByVal breedSize As String) As DataSet
Dim dsa As New DataSet
If breedSize = "Small Breed" Then
sqlStr = "Select price_small_breed, discount_small_breed From tblServicePrice Where service_id = " + serviceId + ""
ElseIf breedSize = "Medium Breed" Then
sqlStr = "Select price_medium_breed, discount_medium_breed From tblServicePrice Where service_id = " + serviceId + ""
ElseIf breedSize = "Big Breed" Then
sqlStr = "Select price_big_breed, discount_big_breed From tblServicePrice Where service_id = " + serviceId + ""
End If
dsa.Clear()
da = New OleDbDataAdapter(sqlStr, con.ConnectionString)
da.Fill(dsa, "getPrice")
Return dsa
End Function
this is my previous code..
Public Function getPrice(ByVal serviceId As String, ByVal breedSize As String)
If breedSize = "Small Breed" Then
sqlStr = "Select price_small_breed, discount_small_breed From tblServicePrice Where service_id = " + serviceId + ""
ElseIf breedSize = "Medium Breed" Then
sqlStr = "Select price_medium_breed, discount_medium_breed From tblServicePrice Where service_id = " + serviceId + ""
ElseIf breedSize = "Big Breed" Then
sqlStr = "Select price_big_breed, discount_big_breed From tblServicePrice Where service_id = " + serviceId + ""
End If
ds.Clear()
da = New OleDbDataAdapter(sqlStr, con.ConnectionString)
da.Fill(ds, "getPrice")
Return ds
End Function