how to display database into combobox - vb.net

im getting error in combobox, instead the combobox display the database... it shows combobox.text = "System.Data.DataRowView" inside.
Private Sub FillCombo()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT subject FROM student order by subject")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "ItemName"
cmbsection.DataSource = ds.Tables(0)
cmbsection.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub

I think this is a simple case of setting the Datasource before the Valuemember.
cmbsection.DataSource = ds.Tables(0)
cmbsection.ValueMember = "ItemName"

Try this
Private Sub FillCombo()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT subject FROM student order by subject")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "ItemName"
cmbsection.DataSource = ds;
cmbsection.SelectedIndex = 0;
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try

You need to set the
cmbsection.DisplayMember = "Subject"
cmbsection.ValueMember = "Subject"

Private Sub FillCombo()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT subject FROM student order by subject")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.Items.clear
For i as Integer = 0 to ds.Tables(0).rows.count-1
cmbsection.Items.add( ds.Tables(0).rows(i).item("subject").tostring)
next
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub

Public Sub LoadProvince()
Dim cn As New SqlConnection("server=.\LENOVO;uid=sa;pwd=123;database=SchoolDb;")
cn.Open()
Dim cmd As New SqlCommand("SELECT * FROM Product;", cn)
Dim dr = cmd.ExecuteReader()
Dim dt As New DataTable()
dt.Load(dr)
dr.Close()
cboPROVINCE.DisplayMember = "Product_NAME"
cboPROVINCE.ValueMember = "Product_Id"
cboPROVINCE.DataSource = dt
End Sub

Related

How to add dynamic Data in to the datagridviewcombobox column?

I am Developing VB.net application.
In that application I take DataGirdView to display data.
I took DataSource property of the datagridview to display 3 columns' data directly from database.
After those columns I add another DataGridViewComboBoxColumn. Then I a want to add dynamic the data into that ComboBoxColumn.
how to do this?
Private Function CreatComboBoxWithEnum() As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Dim adpter As New SqlDataAdapter
Dim ds As New DataTable
Try
Sqlconn.Open()
Dim Query As String
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr ='" & val & "' "
COMMAND = New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = COMMAND
adpter.Fill(ds)
combo.DataSource = ds
combo.DataPropertyName = "OperationNo"
combo.Name = "OperationNo"
OperationNo.ValueMember = "OperationNo"
OperationNo.DisplayMember = "OperationNo"
Next
Sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return combo
End Function
Private Sub load_operationNo()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Try
op.Name = "OperationNo"
DataGridView1.Columns.Add(op)
Sqlconn.Open()
Dim Query As String
Dim i As Integer = 0
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim OPno As New DataGridViewComboBoxCell
With OPno
Dim adpter As New SqlDataAdapter
Dim dt As New DataTable
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr = " & val & " order by sr"
Using cmd As New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = cmd
adpter.Fill(dt)
End Using
.DataSource = dt
.ValueMember = "OperationNo"
.DisplayMember = "OperationNo"
DataGridView1.Rows(i).Cells("OperationNo") = OPno
i = i + 1
End With
Next
Sqlconn.Close()
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
End Sub
This is the code to add dynamically add the data into DatagridViewComboboxColumn

Save and Update from Datagridview to Access Database

i've been fumbling with this problem for a while now. am trying to update/insert into my access database data from a datagridview on a form.
i've a maskedtextbox that i've masked to suit my primary key. when the mask is completed then automatically, records are read from the database to the textboxes and datagridview as shown in the attached picture.
i did that with this code
If STHN_ID.MaskCompleted = True Then
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
'da = New OleDbDataAdapter("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn) 'Change items to your database name
'da.Fill(ds)
'Dim view As New DataView(tables(0))
'source1.DataSource = view
'DependantView.DataSource = view
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
'connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DependantView.DataSource = myTable
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
my headache now is to update/insert into the database when records are added/edited in the datagridview based on the STHN_ID entered in the maskedtextbox. any help would be really appreciated.
sample
this is how i got it done!
on maskedtextbox with mask completed this is the code to read from database and load datagridview ...........
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
con = New OleDbConnection
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\PRINCE\Documents\STHNDatabase.accdb")
con.Open()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
Dim connection As New OleDbConnection
connection.ConnectionString = connString
adapt = New OleDbDataAdapter("Select [DependentID],[DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship],[STHN_ID] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", con)
ds = New DataSet
adapt.Fill(ds, "DependantData")
DependantView.DataSource = ds.Tables(0)
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
and on the SaveButton Click this is the code.....
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Try
builder = New OleDbCommandBuilder(adapt)
adapt.Update(ds, "DependantData")
MsgBox("Updated Successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks once again. really appreciate it

Am new to asp.net and vb.net.,now am trying to make a gridview of a database table

now am trying to make a gridview of a database table named UploadProject.while selecting row of gridview display image in seperate image field by using imageurl At the time of compiling of following code image not displayed.an error occured..."incorect syntax near '='".Any body please help me to solve this problem
Protected Sub OnSelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
lblimageid.Text = row.Cells(0).Text
lbltitle.Text = row.Cells(1).Text
get_Address()
get_Image()
End Sub
Public Sub get_Address()
Dim qry As String
Try
cn.Open()
qry = "select (title,imageurl) from [UploadProject] where [id] = '" & lblimageid.Text & "'"
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes2.ForeColor = Drawing.Color.Red
lblmes2.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub get_Image()
Dim qry As String
Try
cn.Open()
qry = "select title,imageurl from UploadProject where id = " & lblimageid.Text
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes1.ForeColor = Drawing.Color.Red
lblmes1.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub getProjectDT()
Dim qry As String
Try
qry = "select id,title,date from UploadProject "
sda = New SqlDataAdapter(qry, cn)
ds = New DataSet
sda.Fill(ds, "UploadProject")
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Catch ex As Exception
Finally
cn.Close()
End Try
End Sub

Trouble loading data into textbox

Upon the click of a button, I want the program to load in details about the user (stored in an access database) into the textboxes.
This is what I have to far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Documents\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
Try
MyConn.Open()
da = New OleDbDataAdapter("Select * from tbl_employees WHERE FirstName = """ & EmployeeLogin.usersname & """", MyConn)
ds = New DataSet
da.Fill(ds)
TextBox1.Text = ds.Tables("tbl_employees").Rows(0).Item(2)
MyConn.Close()
Catch ex As Exception
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
End Sub
any idea why this isn't working? thanks

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