How to make a default item for ComboBox with a DataSource - vb.net

In my application I have a data bound ComboBox that looks like this:
Dim listaCategoria As List(Of Ccategoria) = CAD.ObterTodosC()
cbxAlterarCg.DataSource = listaCategoria
cbxAlterarCg.DisplayMember = "nomeCategoria"
cbxAlterarCg.ValueMember = "idCategoria"
The class code (CAD):
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
And the attributes:
Public Class Ccategoria
Private _idCategoria As Integer
Private _nomeCategoria As String
(...)
My ComboBox displays "nomeCategoria" with the "idCategoria" value right.
Now my question, like the title says can I create a default read only item so saying ("select your category") or something like that?
I've seen some other tutorials but none of them with ComboBox which are data bounded.

What you could do is add a Ccategoria() to lstTodos just under Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria) like so:
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
In doing this you are simply adding to the DataSource. You could then look into providing validation by checking to see if idCategoria is 0. If it is you may want to consider showing a MessageBox to the user prompting them to pick a category.

Related

display a warning message when an exception occurs

i have a webservice that inserts, delete, updates the data from or to a database. so in this particular form it has a foreign key. so basically it should only accept values which are present in the primarty table.
when user enters any other value a exception occurs.
How do I make sure that such type of SQL exception when caught, a user friendly custom error message(Such as the entered ID doesn't exist.Data insertion failed!) is passed from my web service.
Thanks a lot.
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()>
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")>
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ToolboxItem(False)>
Public Class WebService2
Inherits System.Web.Services.WebService
Public Class Details
Public Property CardID As Integer
Public Property BookID As Integer
Public Property IssuedBy As String
End Class
<WebMethod>
Public Sub AddBook(ByVal emp As Details)
Dim cs1 As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con1 As SqlConnection = New SqlConnection(cs1)
Dim thequery As String = "select * from BookIssue where CardID=#CardID"
Dim cmd1 As SqlCommand = New SqlCommand(thequery, con1)
cmd1.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
con1.Open()
Dim reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MsgBox("ID Number is Already in use")
con1.Close()
Else
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spInsertIntoBookIssue", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#BookID",
.Value = emp.BookID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#IssuedBy",
.Value = emp.IssuedBy
})
con.Open()
cmd.ExecuteNonQuery()
MsgBox("Data Inserted")
End Using
End If
End Using
End Sub
<WebMethod>
Public Sub GetAllDetails()
Dim listEmployees As List(Of Details) = New List(Of Details)()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("Select * from BookIssue", con)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Dim details As Details = New Details()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
listEmployees.Add(details)
End While
End Using
Dim js As JavaScriptSerializer = New JavaScriptSerializer()
Context.Response.Write(js.Serialize(listEmployees))
End Sub
<WebMethod>
Public Sub GetAllDetails1()
Dim listEmployees As List(Of Details) = New List(Of Details)()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("Select * from BookIssue", con)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Dim details As Details = New Details()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
listEmployees.Add(details)
End While
End Using
Dim js As JavaScriptSerializer = New JavaScriptSerializer()
Context.Response.Write(js.Serialize(listEmployees))
End Sub
<WebMethod>
Public Function GetdetailsById(ByVal CardID As Integer) As Details
Dim details As Details = New Details()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spGetBookIssueDetailsByCardID", con)
cmd.CommandType = CommandType.StoredProcedure
Dim parameter As SqlParameter = New SqlParameter()
parameter.ParameterName = "#CardID"
parameter.Value = CardID
cmd.Parameters.Add(parameter)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
End While
End Using
Return details
End Function
<WebMethod>
Public Function GetdetailsById1(ByVal CardID As Integer) As Details
Dim details As Details = New Details()
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spGetBookIssueDetailsByCardID1", con)
cmd.CommandType = CommandType.StoredProcedure
Dim parameter As SqlParameter = New SqlParameter()
parameter.ParameterName = "#CardID"
parameter.Value = CardID
cmd.Parameters.Add(parameter)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
details.CardID = Convert.ToInt32(rdr("CardID"))
details.BookID = Convert.ToInt32(rdr("BookID"))
details.IssuedBy = rdr("IssuedBy").ToString()
End While
End Using
Return details
End Function
<WebMethod>
Public Sub DeleteRecord1(ByVal emp As Details)
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spDeleteByID", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
<WebMethod>
Public Sub Update(ByVal emp As Details)
Dim cs As String = ConfigurationManager.ConnectionStrings("library management systemConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(cs)
Dim cmd As SqlCommand = New SqlCommand("spUpdateBookIssue", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#BookID",
.Value = emp.BookID
})
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#IssuedBy",
.Value = emp.IssuedBy
})
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
End Class
I suggest modeling your code off this example, i modified the delete sub you provided to include a catch with a custom ErrorRoutine for unhandled cases, otherwise you can obtain the number of deleted rows from the executeNonQuery() function. I also chnaged so we return the number of deleted rows, this way if its less than 1 you can do whatever you want with messages after calling the delete.
Public Sub DeleteRecord1(ByVal emp As Details) As Integer
Dim cs As String = ConfigurationManager.ConnectionStrings("library management
systemConnectionString").ConnectionString
Dim m_RowsDeleted As Integer
Dim con As SqlConnection = New SqlConnection(cs)
Try
Using con
Dim cmd As SqlCommand = New SqlCommand("spDeleteByID", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter() With {
.ParameterName = "#CardID",
.Value = emp.CardID
})
con.Open()
m_RowsDeleted = cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
ErrorRoutine(ex, "Delete")
Finally
If Not IsNothing(con) Then
If con.State = ConnectionState.Open Then
con.Close()
End If
End If
End Try
Return m_RowsDeleted
End Sub

Update table in sql database from listview items

Hello folks am trying read from the table identify a specific column if not YES then update my table using items from listview
Public Sub FeesFromSetFees(lst As ListView, Amt As String, Year As String, Clss As String, Term As String, Mode As String)
Dim txtID As New TextBox
Dim txtbal As New TextBox
Dim toText As New TextBox
Dim add As New TextBox
Try
con = New SqlConnection(My.Settings.DeseretConnectionString)
con.Open()
sql = "SELECT * FROM Fees"
command = New SqlCommand(sql, con)
reader = command.ExecuteReader
While reader.Read()
toText.Text = reader.Item("scholarship").ToString
If toText.Text.ToUpper <> "YES" Then
txtID.Text = reader.Item("id").ToString
add.Text = reader.Item("balance").ToString
txtbal.Text = CType(Amt.Trim, Double) + CType(add.Text.Trim, Double)
Dim item As New ListViewItem(txtbal.Text)
item.SubItems.Add(txtID.Text)
lst.Items.Add(item)
Dim lstId As New List(Of String)
Dim lstBalance As New List(Of String)
For Each li As ListViewItem In lst.Items
lstId.Add(li.SubItems(0).ToString)
lstBalance.Add(li.SubItems(1).ToString)
Next
Dim Sql = "Update fees Set class = #Class, year = #Year, mode = #Mode,term = #Term, balance = #Balance where id = #ID"
Using cn As New SqlConnection(My.Settings.DeseretConnectionString)
Using cmd As New SqlCommand(Sql, cn)
With cmd.Parameters
.Add("#Class", SqlDbType.VarChar).Value = Clss
.Add("#Year", SqlDbType.VarChar).Value = Year
.Add("#Mode", SqlDbType.VarChar).Value = Mode
.Add("#Term", SqlDbType.VarChar).Value = Term
.Add("#Balance", SqlDbType.VarChar)
.Add("#ID", SqlDbType.VarChar)
End With
cn.Open()
For index = 0 To lstId.Count - 1
cmd.Parameters("#Balance").Value = lstBalance(index)
cmd.Parameters("#ID").Value = lstId(index)
cmd.ExecuteNonQuery()
Next
End Using
End Using
MessageBox.Show("successful")
End If
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
I get my successful message but nothing really happen to data in the table
Public Sub FeesFromSetFees(Amt As String, Year As String, Clss As String, Term As String, Mode As String)
Dim txtID As New TextBox
Dim txtbal As New TextBox
Dim toText As New TextBox
Dim add As New TextBox
Try
con = New SqlConnection(My.Settings.DeseretConnectionString)
con.Open()
sql = "SELECT * FROM Fees"
command = New SqlCommand(sql, con)
reader = command.ExecuteReader
While reader.Read()
toText.Text = reader.Item("scholarship").ToString
If toText.Text.ToUpper <> "YES" Then
txtID.Text = reader.Item("id").ToString
add.Text = reader.Item("balance").ToString
txtbal.Text = CType(Amt.Trim, Double) + CType(add.Text.Trim, Double)
Dim Sql = "Update fees Set class = #Class, year = #Year, mode = #Mode,term = #Term, balance = #Balance where id = #ID"
Using cn As New SqlConnection(My.Settings.DeseretConnectionString)
Using cmd As New SqlCommand(Sql, cn)
With cmd.Parameters
.Add("#Class", SqlDbType.VarChar).Value = Clss
.Add("#Year", SqlDbType.VarChar).Value = Year
.Add("#Mode", SqlDbType.VarChar).Value = Mode
.Add("#Term", SqlDbType.VarChar).Value = Term
.Add("#Balance", SqlDbType.VarChar).Value = txtbal.Text
.Add("#ID", SqlDbType.VarChar).Value = txtID.Text
cn.Open()
cmd.ExecuteNonQuery()
End With
End Using
End Using
MessageBox.Show("successful")
End If
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

How to use array in vb.net for combobox usage

Let me say that i want to return some array by using this method
Function getKategori() As String()
Dim a As String() = {}
Try
connection.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = connection
myCommand.CommandText = "SELECT * FROM kategori"
myAdapter.SelectCommand = myCommand
reader = myCommand.ExecuteReader
While reader.Read()
a = {reader(0).ToString, reader(1).ToString}
End While
Catch ex As Exception
End Try
Return a
End Function
it should be return as like
{{a,b},{a,b}} etc, and i want to use that result into combo box by using foreach method
For Each k In x.getKategori()
'?some function to add these items into combobox?
Next
How should i do for it?

datagridview not showing the first row vb.net

hi so i have this list that im currently using on a combobox that's why i have the idcategoria = 0 with the nomeCategoria = "Select your Category"so the combobox default item would be "select your category".
here is the code of the list
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
Now i want to use the same list on a datagridview and i wanted to know if there is a way to not show the id = 0 on the datagridview or do i have to create another list without the idCategorie = 0 for the datagridview, any ideas on this? thanks
Create another list from already loaded
Dim newList = lstTodos.Skip(1).ToList()
Skip method will return new collection without first item.
Notice that this approach will work only when - Select your Category - item is a first item in the list.
Or change your method to return list without - Select your Category - item and add it only when you need.
Public Shared Iterator Function ObterTodosC() As IEnumerable(Of Ccategoria)
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Yield New Ccategoria With
{
.IdCategoria = reader.GetInt32(0),
.NomeCategoria = reader.GetString(1)
}
End While
End Using
End Using
End Function
Then you can create list of categories for datagridview
Dim forDataGridView = ObterTodosC().ToList()
Dim notSelectedCategory As New Ccategoria With
{
.IdCategoria = 0,
.NomeCategoria = "select your category"
}
Dim forComboBox = forDataGridView.ToList()
forComboBox.Insert(0, notSelectedCategory)
With this approach your remove side effect from ObterTodosC method.
So method responsibility will be only load items from database

error :ExecuteNonQuery: CommandText property has not been initialized

this code is in the button click , i get each data out using spilt
but i encounter error at "cmd.CommandType = CommandType.Text"
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
the same code , the below work
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO GuestList (groupID,guest,contact,eEmail,relationship,info,customerID) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5), Session("customerID"))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
You never set the CommandText property.
You don't need to set CommandType at all.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
dim dt as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblGender )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox1
.DataSource = dt
.DisplayMember = "Gender"
End With
dim dt1 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblStatus )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox2
.DataSource = dt1
.DisplayMember = "Status"
End With
dim dt2 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblDepartment )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox3
.DataSource = dt2
.DisplayMember = "Department"
End With
End Sub
See this
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
'Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
'If item.Contains(",") Then
' splitItems = item.Split(",".ToCharArray())
' sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
'End If
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}({1},'{2}'); ", sqlStatement, splitItems(0), splitItems(1))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try