Private Sub ButtonComSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonComSave.Click
Dim ComNamDis As String
Dim ComPro1 As String
Dim ComPro2 As String
Dim ComPro3 As String
Dim msg As MsgBoxResult
If ButtonComSave.Text = "Save" Then
ComNamDis = "Insert Into ComNamDis (Com_Code, Com_Name, Com_Discreption) Values(#Com_Code, #Com_Name, #Com_Discreption)"
ComPro1 = "Insert Into ComPro (Com_Code, ComTyp, PriCat_Code, SubCat_Code, StoUni_Code, CalTyp_Code, CosTyp_Code, MiniW, MiniD, MiniH, MiniU, MiniQ, Local_Cost, "
ComPro2 = "Last_Cost, Profit_Margin, Price) Values(#Com_Code, #ComTyp, #PriCat_Code, #SubCat_Code, #StoUni_Code, #CalTyp_Code, #CosTyp_Code, #MiniW, #MiniD, #MiniH, "
ComPro3 = "#MiniU, #MiniQ, #Local_Cost, #Last_Cost, #Profit_Margin, #Price)"
msg = MsgBox("You are sure to save this component ?", MsgBoxStyle.YesNo, "Confirm")
Else
ComNamDis = "Update ComNamDis set Com_Code = #Com_Code, Com_Name = #Com_Name, Com_Discreption = #Com_Discreption Where Com_Code = '" & txtComCod.Text & "'"
ComPro1 = "Update ComPro set Com_Code = #Com_Code, ComTyp = #ComTyp, PriCat_Code = #PriCat_Code, SubCat_Code = #SubCat_Code, StoUni_Code = #StoUni_Code, "
ComPro2 = "CalTyp_Code = #CalTyp_Code, CosTyp_Code = #CosTyp_Code, MiniW = #MiniW, MiniD = #MiniD, MiniH = #MiniH, MiniU = #MiniU, MiniQ = #MiniQ, "
ComPro3 = "Local_Cost = #Local_Cost, Last_Cost = #Last_Cost, Profit_Margin = #Profit_Margin, Price = #Price Where Com_Code = '" & txtComCod.Text & "'"
msg = MsgBox("You are sure to edit this component ?", MsgBoxStyle.YesNo, "Confirm")
End If
If msg = MsgBoxResult.Yes Then
Try
Dim cmdComNamDis As New OleDbCommand(ComNamDis, Conn)
cmdComNamDis.Parameters.Add(New OleDbParameter("#Com_Code", OleDbType.VarChar)).Value = txtComCod.Text
cmdComNamDis.Parameters.Add(New OleDbParameter("#Com_Name", OleDbType.VarChar)).Value = txtComNam.Text
cmdComNamDis.Parameters.Add(New OleDbParameter("#Com_Discreption", OleDbType.VarChar)).Value = txtComDis.Text
Conn.Open()
cmdComNamDis.ExecuteNonQuery()
Dim cmdCompro As New OleDbCommand(ComPro1 & ComPro2 & ComPro3, Conn)
cmdCompro.Parameters.Add(New OleDbParameter("#Com_Code", OleDbType.VarChar)).Value = txtComCod.Text
cmdCompro.Parameters.Add(New OleDbParameter("#ComTyp", OleDbType.VarChar)).Value = ComboBoxComTyp.Text
cmdCompro.Parameters.Add(New OleDbParameter("#PriCat_Code", OleDbType.VarChar)).Value = ComboBoxPriCat.ValueMember
cmdCompro.Parameters.Add(New OleDbParameter("#SubCat_Code", OleDbType.VarChar)).Value = ComboBoxSubCat.ValueMember
cmdCompro.Parameters.Add(New OleDbParameter("#StoUni_Code", OleDbType.VarChar)).Value = ComboBoxComStoUni.ValueMember
cmdCompro.Parameters.Add(New OleDbParameter("#CalTyp_Code", OleDbType.VarChar)).Value = ComboBoxComCalcolation.ValueMember
cmdCompro.Parameters.Add(New OleDbParameter("#CosTyp_Code", OleDbType.VarChar)).Value = ComboBoxComCostTyp.ValueMember
'i think here it's Problem
cmdCompro.Parameters.Add(New OleDbParameter("#MiniW", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComMiniW.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#MiniD", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComMiniD.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#MiniH", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComMiniH.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#MiniU", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComMiniU.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#MiniQ", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComMiniQ.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#Local_Cost", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComLocalCost.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#Last_Cost", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComLastCost.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#Profit_Margin", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComProfitMargin.Text)
cmdCompro.Parameters.Add(New OleDbParameter("#Price", OleDbType.Decimal)).Value = Convert.ToDecimal(txtComPrice.Text)
cmdCompro.ExecuteNonQuery()
If ButtonComSave.Text = "Save" Then
MsgBox("The component has been saved successfully :) ", MsgBoxStyle.Information, "Confirm")
Else
MsgBox("The component has been Edited successfully :) ", MsgBoxStyle.Information, "Confirm")
End If
ButtonComNew_Click(sender, e)
Catch ex As Exception
MsgBox(ex.Message)
Finally
Conn.Close()
End Try
Else
Exit Sub
End If
End Sub
Connections and Commands need to be closed and disposed. Keep your connection objects local to method where the connection is used. Then you can use Using...End Using blocks to do the close, dispose.
Your validation could be done in the TextBox's Validating Event and use the ErrProvider. If you want to do it here in the Button.Click, do it at the beginning of the Sub.
Dim ComMiniW As Decimal
If Not Decimal.TryParse(txtComMiniW.Text, ComMiniW) Then
MessageBox.Show("ComMinW must be a valid number")
Exit Sub
End If
The down in the Parameters use the converted decimal variable.
cmdCompro.Parameters.Add(New OleDbParameter("#MiniW", OleDbType.Decimal)).Value = ComMiniW
Do this for each of the TextBoxes that require decimal values.
If (TextBoxStudentID.Text.ToString().Trim() <> "") Then
Dim adp1 As SqlDataAdapter = New SqlDataAdapter("select StudentName, StudentStandard, StudentBalance, EmailAddress, ContactNumber Active from StudentDetails where StudentID = '" + TextBoxStudentID.Text.ToString() + "'", con)
Dim ds1 As DataSet = New DataSet()
adp1.Fill(ds1)
If ds1.Tables.Count > 0 Then
If ds1.Tables(0).Rows.Count > 0 Then
TextBoxStudentName.Text = ds1.Tables(0).Rows(0)(0).ToString()
TextBoxStudentStd.Text = ds1.Tables(0).Rows(0)(1).ToString()
TextBoxCurrentBalance.Text = ds1.Tables(0).Rows(0)(2).ToString()
CheckBoxActive.Checked = Convert.ToBoolean(ds1.Tables(0).Rows(0)(3).ToString())
Else
MessageBox.Show("No student found for Student ID = " + TextBoxStudentID.Text.ToString(), "Search failed!")
TextBoxStudentName.Text = ""
TextBoxStudentStd.Text = ""
TextBoxCurrentBalance.Text = ""
TextBoxContactNumber.Text = ""
CheckBoxActive.Checked = False
End If
End If
End If
I wrote the above code to search for a particular roll number in the database I called. The error says "the string is not a valid boolean". kindly help.
Try:
Convert.ToBoolean(ds1.Tables(0).Rows(0)(5).ToString())
Column 3 is the email address. Also add a comma between ContactNumber and Active
I was wondering if it was possible to filter down data from a table using multiple values from a checkboxlist? (or any other way) I have a checkboxlist and a gridview and when you check on of the boxes it does show the right data in the gridview but the problem arises when I try to check multiple values. It seems to search for the first checked value and then ignores the rest. You'd think it'd be simple! Perhaps it is. Here is my attempt below.
CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
Dim strSQL As New System.Text.StringBuilder
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
FillGridView()
End If
End Sub
Private Sub FillGridView()
Dim strMyConn As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
Using MyConn As New SqlClient.SqlConnection(strMyConn)
MyConn.Open()
Dim cmd As New SqlClient.SqlCommand(strSQL.ToString, MyConn)
cmd.Connection = MyConn
cmd.CommandType = CommandType.Text
Try
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Using
If Me.GridView1.Visible = False Then Me.GridView1.Visible = True
Catch ex As Exception
Me.GridView1.Visible = False
End Try
End Using
End Sub
Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
If c <> 0 Then
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
End If
End Sub
End Class
Refactor this section to create a WHERE IN statement so it checks to see if the value is found among any item checked
Before
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
After
Dim params As StringBuilder = New StringBuilder()
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
params.Append("'")
params.Append(CheckBoxList1.Items(i).Text)
If i < Me.CheckBoxList1.Items.Count Then
params.Append("',") // don't append a comma if it's the last item
End If
End If
Next
strSQL.Append("SELECT Project.* FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID WHERE Keyword.Keyword in (")
strSQL.Append(params.ToString()) // append comma delimited values that make up where in statement
strSQL.Append("')") // close where in statement
FillGridView()
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
i am importing excel file in datagridview below is my code
'ofdImport.Filter = "Excel Files (*.xls)|*.xls"
ofdImport.FileName = ""
If ofdImport.ShowDialog(Me) = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
txtPath.Text = ofdImport.FileName
If txtPath.Text <> "" Then
chkItemList.Visible = True
dgvImportData.Visible = True
pnlDataMsg.Visible = False
dgvImportData.Columns.Clear()
chkItemList.Items.Clear()
Try
Dim conExcel As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & txtPath.Text & " '; Extended Properties=Excel 8.0;")
Dim excelSelect As New OleDbCommand
Dim excelAdp As New OleDbDataAdapter
Dim excelSchemaDt As DataTable
Dim dset As New DataSet
If conExcel.State Then conExcel.Close()
conExcel.Open()
excelSelect.Connection = conExcel
excelSchemaDt = conExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim sheetName As String = excelSchemaDt.Rows(0)("TABLE_NAME").ToString()
excelSelect.CommandText = "select * from [" & sheetName & "] "
excelAdp.SelectCommand = excelSelect
excelAdp.TableMappings.Add("Table", "TestTable")
excelAdp.Fill(dset)
dgvImportData.DataSource = dset.Tables(0)
Dim i As Integer
Dim q(dgvImportData.Columns.Count()) As String
For i = 0 To (dgvImportData.Columns.Count - 1)
q(i) = (dgvImportData.Columns(i).HeaderText.ToString())
Next i
conExcel.Close()
i = 0
Dim a As String = ""
'Dim q(frmImportWizard.gridImport.Columns.Count()) As String
For i = 0 To dgvImportData.Columns.Count - 1
a = dgvImportData.Columns(i).HeaderText.ToString()
'CheckedListBox1.Items.Add(a)
chkItemList.Items.Add(a)
Next i
chkAll.Visible = True
chkAll.Checked = False
lblColumnData.Visible = True
Catch ex As Exception
'MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
End If
excel file contains phone nos for eg "9874532146/8456663225" in one colms and also i have "98455566966" in same colmns
the problem here is my code is not reading the phone numbers
without "/" its going blank in grid
please help
replaced connection string
Dim conExcel As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & txtPath.Text & "';Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""")