in my form, when i modify data i'm getting error as
'Command text was not set for the command object'
I'm using oledb connection
Following us my code
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
sql = "select * from Employee"
conn = New OleDbConnection(s)
adapt = New OleDbDataAdapter(sql, conn)
ds = New DataSet
usql = "Update Employee set enp_name=?, emp_addr=?, DOB=?, DOJ=?, emp_mob=?, emp_mail=? where ID=?"
ucmd = New OleDbCommand(isql, conn)
Dim date1 As Date
date1 = DateTimePicker1.Value
p = ucmd.Parameters.Add("#emp_name", OleDbType.Char)
p.SourceColumn = "emp_name"
p.SourceVersion = DataRowVersion.Current
p = ucmd.Parameters.Add("#emp_addr", OleDbType.Char)
p.SourceColumn = "emp_addr"
p.SourceVersion = DataRowVersion.Current
p = ucmd.Parameters.Add("#DOB", OleDbType.DBDate)
p.SourceColumn = "DOB"
p.SourceVersion = DataRowVersion.Current
p = ucmd.Parameters.Add("#DOJ", OleDbType.DBDate)
p.SourceColumn = "DOJ"
p.SourceVersion = DataRowVersion.Current
p = ucmd.Parameters.Add("#emp_mob", OleDbType.Integer)
p.SourceColumn = "emp_mob"
p.SourceVersion = DataRowVersion.Current
p = ucmd.Parameters.Add("#emp_mail", OleDbType.Char)
p.SourceColumn = "emp_mail"
p.SourceVersion = DataRowVersion.Current
p = ucmd.Parameters.Add("#ID", OleDbType.Integer)
p.SourceColumn = "ID"
p.SourceVersion = DataRowVersion.Current
adapt.UpdateCommand = ucmd
conn.Open()
If conn.State = ConnectionState.Open Then
adapt.MissingSchemaAction = MissingSchemaAction.AddWithKey
adapt.Fill(ds, "ABC")
'conn.Close()
End If
tables = ds.Tables
table = tables("ABC")
rows = table.Rows
cols = table.Columns
row = rows.Find(TextBox1.Text)
row.BeginEdit()
row("ID") = TextBox1.Text
row("emp_name") = TextBox2.Text
row("emp_addr") = TextBox3.Text
row("DOB") = DateTimePicker1.Text
row("DOJ") = DateTimePicker2.Text
row("emp_mob") = TextBox4.Text
row("emp_mail") = TextBox5.Text
row.EndEdit()
'conn.Open()
adapt.Update(ds, "ABC")** Getting error on this line
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
But i'm not getting where i'm going wrong.... please help me
You are not setting usql to the ucmd anywhere.
ucmd.CommandText = usql;
Or rather, in your constuctor:
ucmd = New OleDbCommand(isql, conn)
isql should probably be usql. I am guessing there is an isql string field in the class if you are not getting compilation errors.
Related
I have a windows form with various textboxes and 1 label, the label Identifies my ID in my database, I essentially want to search find the record using the label (ID) and then update the row with the data in the textboxes.
I get syntax error when I carry out ds.update(da)
any ideas? I have no idea what it is holding me back I am assuming it is something silly.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ds As New DataTable
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Dim conn As New OleDb.OleDbConnection(connString)
sql = "SELECT * FROM [STG] WHERE [ID] like '" & Label15.Text & "%'" 'LABEL 15 CONTAINS DATABASE ID
da = New OleDbDataAdapter(sql, conn)
ds = New DataTable
conn.Open()
da.Fill(ds)
'conn.Close()
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Rows(0).Item(1) = KKSTextbox.Text
ds.Rows(0).Item(1) = KKSTextbox.Text 'DATA I WISH TO STORE IN MY DATABASE
ds.Rows(0).Item(2) = TypeTextbox.Text
ds.Rows(0).Item(3) = RangeTextBox.Text
ds.Rows(0).Item(4) = CompDescTextbox.Text
ds.Rows(0).Item(5) = LRTextBox.Text
ds.Rows(0).Item(6) = FuncLocTextbox.Text
ds.Rows(0).Item(7) = LocTextbox.Text
ds.Rows(0).Item(8) = MANTextBox.Text
ds.Rows(0).Item(9) = PTNOTextBox.Text
ds.Rows(0).Item(10) = SUPPTextBox.Text
ds.Rows(0).Item(11) = DetailTextBox.Text
ds.Rows(0).Item(12) = PIDTextBox.Text
ds.Rows(0).Item(13) = CONNTextBox.Text
ds.Rows(0).Item(14) = BLOCKTextBox.Text
ds.Rows(0).Item(15) = OMTextBox.Text
ds.Rows(0).Item(16) = AL1TextBox.Text
ds.Rows(0).Item(17) = AL2TextBox.Text
ds.Rows(0).Item(18) = AL3TextBox.Text
ds.Rows(0).Item(19) = AL4TextBox.Text
ds.Rows(0).Item(20) = AL5TextBox.Text
ds.Rows(0).Item(21) = AL6TextBox.Text
ds.Rows(0).Item(22) = AL7TextBox.Text
ds.Rows(0).Item(23) = AL8TextBox.Text
ds.Rows(0).Item(24) = AL9TextBox.Text
ds.Rows(0).Item(25) = AL10TextBox.Text
ds.Rows(0).Item(26) = EFF1TextBox.Text
ds.Rows(0).Item(27) = EFF2TextBox.Text
ds.Rows(0).Item(28) = EFF3TextBox.Text
ds.Rows(0).Item(29) = EFF4TextBox.Text
ds.Rows(0).Item(30) = EFF5TextBox.Text
ds.Rows(0).Item(31) = EFF6TextBox.Text
ds.Rows(0).Item(32) = EFF7TextBox.Text
ds.Rows(0).Item(33) = EFF8TextBox.Text
ds.Rows(0).Item(34) = EFF9TextBox.Text
ds.Rows(0).Item(35) = EFF10TextBox.Text
ds.Rows(0).Item(36) = SET1TextBox.Text
ds.Rows(0).Item(37) = SET2TextBox.Text
ds.Rows(0).Item(38) = SET3TextBox.Text
ds.Rows(0).Item(39) = SET4TextBox.Text
ds.Rows(0).Item(40) = SET5TextBox.Text
ds.Rows(0).Item(41) = SET6TextBox.Text
ds.Rows(0).Item(42) = SET7TextBox.Text
ds.Rows(0).Item(43) = SET8TextBox.Text
ds.Rows(0).Item(44) = SET9TextBox.Text
ds.Rows(0).Item(45) = SET10TextBox.Text
da.Update(ds)
'da.Dispose() 'I get syntax here
conn.Close()
End Sub
Do use the command builder after the fill
Dim row As DataRow = ds.NewRow
'set all the values for row like row("columnName") = value
ds.Rows.Add(row)
da.Update(ds)
First you need to get a reference to a new row. Then set the values. Then add the new row to the DataTable and finally do the update
No success!
If user of tblcon with billmonth of tbltrns exists in tbltrns then highlight the rows of tblcon with red color
Code:
Private Sub checkexist()
For Each row As DataGridViewRow In DataGridView1.Rows
ConObj = New SqlConnection(ConStr)
ConObj.Open()
Dim qry As String = "SELECT * FROM tblTrns WHERE userName=#userName and bill_month=#bill_month"
CmdObj = New SqlCommand(qry, ConObj)
CmdObj.Parameters.AddWithValue("#bill_month", DateTimePicker1.Text)
CmdObj.Parameters.AddWithValue("#userName", (row.Cells("User").Value.ToString))
drObj = CmdObj.ExecuteReader()
If drObj.HasRows Then
row.DefaultCellStyle.BackColor = Color.Red
End If
Next
ConObj.Close()
End Sub
Query for the Grid
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],connectionstatus[Status] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
Query Changed in getdata but no success. Please guide ...........................................................................................................................................................................................................................................
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],connectionstatus[Status], (SELECT ISNULL(COUNT(*), 0) FROM tblTrns WHERE tblTrns.userName = tblCon.UserName AND bill_month = '" & DateTimePicker1.Text & "') [Comparison] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
I recommend you to fill a new column in your grid with a value for comparison and set it's visibility to false.
You can do that by a subselect or a left join on the second table (if you wish an example just post the query that fills your grid).
Based on your comparison column you can use the CellPainting event of the GridView. Like this:
Private Sub grdGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles grdGridView.CellPainting
If e.RowIndex >= 0 Then
If grdGridView.Rows(e.RowIndex).Cells("colComparison").Value <> "0" And Not IsNothing(grdGridView.Rows(e.RowIndex).Cells("colComparison").Value) Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.SelectionBackColor = Color.IndianRed
End If
End If
End Sub
I know there are a few other posts about putting sql results into a vb.net variable but I just couldn't wrap my head around how they did it and how I could do it in my project.
So what I'm trying to do is query my database for 4 different values and then display each value in a certain part of the form. I was going to store the each value into a variable and then do an textbox1.text = i
Updated code for 10/5/2014
Private Sub LBmembers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
Dim i As String = LBmembers.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime, WorkPercent, Share FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = i
Using reader = cmd.ExecuteReader()
If reader.Read() Then
TBtimestart.Text = reader.ToString(0)
TBtimeend.Text = reader.ToString(1)
Dim j = Convert.ToInt32(reader.ToString(2))
TBtimecycle.Text = reader.GetInt32(3).ToString
TBmemberpercent.Text = reader.GetInt32(4)
TBmembershare.Text = reader.GetInt32(5)
If j = 1 Then
RBpro.Checked = True
ElseIf j = 2 Then
RBret.Checked = True
ElseIf j = 3 Then
RBcov.Checked = True
ElseIf j = 4 Then
RBskiff.Checked = True
ElseIf j = 5 Then
RBmack.Checked = True
ElseIf j = 6 Then
RBhulk.Checked = True
Else
RBpro.Checked = False
RBret.Checked = False
RBcov.Checked = False
RBskiff.Checked = False
RBmack.Checked = False
RBhulk.Checked = False
Exit Sub
End If
End If
End Using
con.Close()
End Using
End Using
End Sub
The exception
InvalidCastException was unhandled Specified cast is not valid.
Pops up on the line TBtimecycle.text = reader.GetInt32(3).ToString
The reader is also reading "System.Data.OleDb.OleDbDataReader" when I insert the test code "TBgrossisk.Text = reader.ToString()" into the using statement
If you look carefully to the syntax of the SELECT statement you will see that you can request any column of the table with just one query.
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
if string.IsNullOrWitheSpace(ListBox1.SelectedItem.ToString()) Then
MessageBox.Show("Select an item from the Listbox")
End If
Dim member As String = ListBox1.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime " & _
"FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = member
Using reader = cmd.ExecuteReader
if reader.Read() Then
TextBox1.Text = reader.GetString(0)
TextBox2.Text = reader.GetString(1)
Dim j = reader.GetInt32(2)
If j = 1 Then
Radio1.Checked = True
ElseIf j = 2 Then
Radio2.Checked = True
ElseIf j = 3 Then
Radio3.Checked = True
ElseIf j = 4 Then
Radio4.Checked = True
ElseIf j = 5 Then
Radio5.Checked = True
ElseIf j = 6 Then
Radio6.Checked = True
Else
Exit Sub
End If
TextBox4.Text = reader.GetInt32(3).ToString()
Else
MessageBox.Show("The search for '" & member & "' doesn't find any data")
End If
End Using
End Using
End Using
End Sub
Instead of using ExecuteScalar that returns just the first column of the first row retrieved you could use an OleDbDataReader returned by the method ExecuteReader. This object allows to access the various column in the current record using an index (or the column name). Read more about OleDbDataReader in MSDN
For the last three hours. I searched the internet for solutions to my problem. I found some but none of them worked (!?). The error is in the btnAdd Sub. I couldn't use this form of declaration: 'DECLARE #cds SqlDBType.SmallInt because I would get the following error: Statement is not valid inside a method/multiline lambda. I also used their form of declaration http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.insertcommand%28v=vs.110%29.aspx but again... I receive the same error. The commented sections are everything I tried. Maybe you can help me solve this. :)
Updated correct solution:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
con.Open()
Dim dr As DataRow
mycmd.CommandText = "insert into studenti(cods, nrmatricol, nume, grupa, datan) values(#cs,#nm,#n,#g,#dn)"
Dim p1 As New SqlParameter
Dim p2 As New SqlParameter
Dim p3 As New SqlParameter
Dim p4 As New SqlParameter
Dim p5 As New SqlParameter
mycmd.Parameters.Clear()
p1.ParameterName = "#cs"
p1.Value = Convert.ToInt16(txtCodS.Text)
mycmd.Parameters.Add(p1)
p2.ParameterName = "#nm"
p2.Value = txtNrMat.Text
mycmd.Parameters.Add(p2)
p3.ParameterName = "#n"
p3.Value = txtNume.Text
mycmd.Parameters.Add(p3)
p4.ParameterName = "#g"
p4.Value = txtGrupa.Text
mycmd.Parameters.Add(p4)
p5.ParameterName = "#dn"
p5.Value = Convert.ToDateTime(txtDataN.Text)
mycmd.Parameters.Add(p5)
mycmd.Connection = con
da1.InsertCommand = mycmd
dr = DataSet1.Tables("studenti").NewRow()
dr("cods") = Convert.ToInt16(txtCodS.Text)
dr("nrmatricol") = txtNrMat.Text
dr("nume") = txtNume.Text
dr("grupa") = txtGrupa.Text
dr("datan") = Convert.ToDateTime(txtDataN.Text)
DataSet1.Tables("studenti").Rows.Add(dr)
da1.Update(DataSet1, "studenti")
UpdateUI()
con.Close()
End Sub
Wrong:
Dim da1 As New SqlClient.SqlDataAdapter
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
con.Open()
Dim dr As DataRow
Dim mycmd As New SqlClient.SqlCommand
//Dim mycmd2 As New SqlClient.SqlCommand
//mycmd2.Connection = con
// mycmd2.CommandText = "select* from studenti"
//Dim v(4) As Object
//v(0) = Convert.ToInt16(txtCodS.Text)
//v(1) = txtNrMat.Text
//v(2) = txtNume.Text
//v(3) = txtGrupa.Text
// v(4) = txtDataN.Text
mycmd.CommandText = "insert into studenti (cods,nrmatricol,nume,grupa,datan) values (#cds,#nm,#n,#g,#dn)"
Dim p1 As New SqlClient.SqlParameter
p1.ParameterName = "#cds"
p1.Value = Convert.ToInt16(txtCodS.Text)
//DECLARE #cds SqlDBType.SmallInt
//cmd.Parameters.Clear()
cmd.Parameters.Add(p1)
//cmd.Parameters.Add("#cds", SqlDbType.SmallInt).Value = Convert.ToInt16(txtCodS.Text)
cmd.Parameters.Add("#nm", SqlDbType.VarChar, 10)
cmd.Parameters.Add("#n", SqlDbType.VarChar, 30)
cmd.Parameters.Add("#g", SqlDbType.VarChar, 10)
cmd.Parameters.Add("#dn", SqlDbType.DateTime)
mycmd.Connection = con
da1.InsertCommand = mycmd
dr = DataSet1.Tables("studenti").NewRow()
dr("cods") = Convert.ToInt16(txtCodS.Text)
dr("nrmatricol") = txtNrMat.Text
dr("nume") = txtNume.Text
dr("grupa") = txtGrupa.Text
dr("datan") = Convert.ToDateTime(txtDataN.Text)
DataSet1.Tables("studenti").Rows.Add(dr)
da1.Update(DataSet1, "studenti")
UpdateUI()
con.Close()
End Sub
End Class
#cds variable is set by after that it is removed by cmd.Parameters.Clear().
Just remove this line of code and provide a value for #cds.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim id As String, sLogon_User As String, sAuth_User As String, sUser_ID As String
Dim sServer_Name As String
Dim sIP_Address As String
sIP_Address = Request.ServerVariables("REMOTE_ADDR")
Dim hit As New PagePosting
Dim currentPosting As Posting = CmsHttpContext.Current.Posting
Dim webContext As WebAuthorContext
webContext = WebAuthorContext.Current
'sNama_Perusahaan = Request.QueryString("sentraID")
'Response.Write("masuk sini dgn nilai = " & CmsHttpContext.Current.CmsQueryString())
sData = ""
If Not Page.IsPostBack Then
'sNama_Perusahaan = Request.ServerVariables("sentraID")
sNama_Perusahaan = Request.QueryString("sentraID")
' sNama_Perusahaan = Request.QueryString("sentraID")
Response.Write("masuk sini dgn nilai = " & Request.QueryString("sentraID") & sNama_Perusahaan)
tampil(sNama_Perusahaan)
End If
Sub tampil(ByVal sParam As String)
Dim rd As SqlDataReader
Dim myConnection = New SqlConnection(ConfigurationSettings.AppSettings("RegBIK"))
myConnection.Open()
Dim adadata As Integer
' Dim myCommand As New SqlCommand("select count (*) from kuesioner where ltrim(rtrim(NmPerush)) ='aaa'", myConnection)
Dim myCommand As New SqlCommand("select count (*) from kuesioner where ltrim(rtrim(NmPerush)) ='&sParam'", myConnection)
rd = myCommand.ExecuteReader
While rd.Read
adadata = rd.GetInt32(0)
End While
myConnection.close()
Try
If adadata > 0 Then
myConnection.Open()
' Dim myCommands As New SqlCommand("select * from kuesioner where ltrim(rtrim(NmPerush)) ='aaa'", myConnection)
Dim myCommands As New SqlCommand("select * from kuesioner where ltrim(rtrim(NmPerush)) ='&sParam'", myConnection)
rd = myCommands.ExecuteReader
While rd.Read
disabledAll()
Me.btnUpload.Enabled = False
Me.btnPreview.Enabled = True
txtNmPerush.Value = rd.GetString(1)
Me.txtNmPemilik.Value = rd.GetString(2)
Me.txtAlmtPerush.Value = rd.GetString(3)
Me.txttlpn.Value = rd.GetString(4)
Me.txtEmail.Value = rd.GetString(5)
Me.txtLamaPerush.Value = rd.GetString(6)
Me.txtJenis.Value = rd.GetString(7)
Me.txtSpesialisasi.Value = rd.GetString(8)
Me.txtkualitas.Value = rd.GetString(9)
Me.txtMerk.Value = rd.GetString(10)
Me.txtStandarPesanan.Value = rd.GetString(11)
Me.txtProduksi.Value = rd.GetString(12)
Me.txtlokal.Value = rd.GetString(13)
Me.txtnasional.Value = rd.GetString(14)
Me.txtekspor.Value = rd.GetString(15)
Me.txtpengalaman.Value = rd.GetString(16)
Me.txtlamaekspor.Value = rd.GetString(17)
Me.txtbiaya.Value = rd.GetString(18)
End While
Else
clearAll()
End If
rd.Close()
myConnection.close()
Catch SQLexc As SqlException
Response.Write("Open Failed. Error Details are: " & SQLexc.ToString())
End Try
End Sub
the source code to get the first parameter, the second to throw codingan parameters to form 2 and the third codingan to read in the form 2..I've tried but still can not
I would think that that code would produce an error, but you did not state that.
To add a parameter to the SQL statement:
Dim myCommand As New SqlCommand("SELECT COUNT(*) FROM kuesioner WHERE LTRIM(RTRIM(NmPerush)) = #param1", myConnection)
myCommand.Parameters.Add(New SqlParameter With {.ParameterName = "param1", _
.SqlDbType = SqlDbType.NVarChar, _
.Size = 200, _
.Value = sParam})
Please alter the .SqlDbType and .Size to match the definition in the database.