How to add dynamic Data in to the datagridviewcombobox column? - vb.net

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

Related

i want to use transaction with my code in VB.NET

I am using SqlDataAdapter and SqlCommandBuilder to insert and update, and I want to use transaction to insert into two tables with this way but I have tried a lot and I didn't succeed
thanks
Dim sql = "select * from ReceiptOfItems where receiptCode=N'" & receiptCode.Text & "' "
Dim dta As New SqlClient.SqlDataAdapter(sql, con)
Dim ds As New DataSet
dta.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
' MsgBox("اسم االتصنيفل او رقمه موجود مسبقا ", MsgBoxStyle.Exclamation, "رسالة تنبيه")
receiptCode.Text = Format(Val(GetLastRecord("ReceiptOfItems", "receiptcode")) + 1, "REC0000000")
End If
Dim dr = dt.NewRow
dr!receiptCode = receiptCode.Text
dr!receiptDate = Format(receiptDate.Value, "yyyy/MM/dd")
' dr!receiptDate = receiptDate.Text
dr!supplierCode = GetsupplierCode(supplierName.Text)
dr!SupplierInvoiceCode = SupplierInvoiceCode.Text
dr!supplierInvoiceDate = Format(supplierInvoiceDate.Value, "yyyy/MM/dd")
'dr!supplierInvoiceDate = supplierInvoiceDate.Text
dr!TotalDiscount = Val(TotalDiscount.Text)
dr!TotalReceipt = Val(TotalReceipt.Text)
dr!TotalArabic = TotalArabic.Text
dr!SupplierInvoiceType = SupplierInvoiceType.Text
dr!salesTax = Val(salesTax.Text)
dr!note = note.Text
dr!status = True
dt.Rows.Add(dr)
Dim cmd As New SqlCommandBuilder(dta)
This should work for you:
con.Open()
Dim trans As SqlTransaction = con.BeginTransaction()
Try
Dim insertStr As String = "insert into ReceiptOfItems (receiptCode, receiptDate, etc.) values(#receiptCode, #receiptDate, #etc)"
Dim insertCmd As New SqlCommand(insertStr, con, trans)
For Each dc As DataColumn In dt.Columns
Dim param As New SqlParameter()
param.ParameterName = dc.ColumnName
param.SourceColumn = dc.ColumnName
insertCmd.Parameters.Add(param)
Next
dta.InsertCommand = insertCmd
dta.Update(ds)
trans.Commit()
con.Close()
Catch ex As Exception
trans.Rollback()
End Try
The DataAdapter class has an UpdateCommand and a DeleteCommand property which must be built appropriately if you are doing something other than inserting new rows.

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

Sending updates from datagridview to existing row in database

I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?
I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()
try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next

How to refresh datagridview without refresh button?

How can I automatically refresh and view the new current datagridview after add or delete?
what code should I put after "msgbox" to view the current data?
Private Sub add()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "INSERT INTO course ( code, description)"
sSQL = sSQL & " VALUES (#cod, #des)"
cmd.CommandText = sSQL
cmd.Parameters.Add("#cod", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtcode.Text)) > 0, Me.txtcode.Text, DBNull.Value)
cmd.Parameters.Add("#des", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtdescription.Text)) > 0, Me.txtdescription.Text, DBNull.Value)
cmd.ExecuteNonQuery()
MsgBox("Data has been save.")
conn.Close()
Catch ex As Exception
MessageBox.Show("Already exist")
End Try
End Sub
You should bind your DataGridView to an appropriate DataSource, e.g. a DataTable.
Then, instead of inserting the data manually in the database, you could use a SqlDataAdapter and the DataTable your DataGridView is bound to.
Here's a simple example:
Dim cons = New SqlConnectionStringBuilder() With
{
.DataSource = "your_server",
.InitialCatalog = "your_db",
.UserID = "your_user",
.Password = "your_password"
}.ConnectionString
Dim con = New SqlConnection(cons)
con.Open()
' create a SqlDataAdapter and provide the SELECT command '
Dim adapter = New SqlDataAdapter()
Dim cb = New SqlCommandBuilder(adapter)
adapter.SelectCommand = New SqlCommand("SELECT code, description FROM course", con)
' the INSERT command can be generated '
adapter.InsertCommand = cb.GetInsertCommand()
' fill a new DataTable with data from database '
Dim dt = New DataTable()
adapter.Fill(dt)
' create a Form with DGV and Insert-Button '
Dim f = New Form()
Dim dgv = New DataGridView() With
{
.DataSource = dt,
.Dock = DockStyle.Fill
}
Dim addButton = New Button() With
{
.Text = "Add new",
.Dock = DockStyle.Bottom
}
Dim i = 0
AddHandler addButton.Click, Function(s, o)
' we insert the new data directly into the DataTable '
dt.Rows.Add(New Object() {"Some","Text"})
' and let the SqlDataAdapter handle the insert '
adapter.Update(dt)
End Function
f.Controls.Add(addButton)
f.Controls.Add(dgv)
f.ShowDialog()
Since the new data is written directly into the DataTable, the DataGridView is updated immediately.
Of course this is even easier when you use TableAdapters.

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