I am using VB.Net to load data from SQL server, institute and country and fill each table in a dataset. Country table has countryId, countryName where countryId as the primary key. Institute has instId, name, countryId columns where countryId as a foreign key taken from country table. I am using bindingSource to navigate through data in table institute and display data in text boxes. In other hand I have a combobox that also has a bindingSource which is the country table. I want now when I navigate the institute table I also get data in my combobx get changed based on the value in institute countryId.
Have a look to the following code:
Private Sub frmSystemOptions_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
dsOptions = New DataSet
loadOptions()
bsInstitute = New BindingSource(dsOptions, "institute")
InstIdTextBox.DataBindings.Add("Text", bsInstitute, "instId")
NameTextBox.DataBindings.Add("Text", bsInstitute, "name")
CountryIdTextBox.DataBindings.Add("Text", bsInstitute, "countryId")
bsCountry = New BindingSource(dsOptions, "country")
cmbCountry.DataSource = bsCountry
cmbCountry.DisplayMember = "countryName"
cmbCountry.ValueMember = "countryId"
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Sub loadOptions()
Dim sql As String
Try
sqlConn = New SqlConnection(connString)
sqlConn.Open()
sql = "select instId, name, countryId from institute"
daInstitute = New SqlDataAdapter(sql, sqlConn)
daInstitute.Fill(dsOptions, "institute")
'----------------------------------------------------------------------
sql = "select countryId, countryName from country"
daAdapter = New SqlDataAdapter(sql, sqlConn)
daAdapter.Fill(dsOptions, "country")
'----------------------------------------------------------------------
sqlConn.Close()
Catch ex As Exception
sqlConn.Close()
MsgBox(Err.Description)
End Try
End Sub
Also for navigation I use the following code:
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
If bsInstitute.Position + 1 < bsInstitute.Count Then
bsInstitute.MoveNext()
Else
bsInstitute.MoveFirst()
End If
Me.Invalidate()
End Sub
Now how can I make the countryName in the combobx changes based on the value of the countryId in the institute table?
You need to bind the combobox as following:
Private Sub frmSystemOptions_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
dsOptions = New DataSet
loadOptions()
bsInstitute = New BindingSource(dsOptions, "institute")
bsCountry = New BindingSource(dsOptions, "country")
InstIdTextBox.DataBindings.Add("Text", bsInstitute, "instId")
NameTextBox.DataBindings.Add("Text", bsInstitute, "name")
CountryIdTextBox.DataBindings.Add("Text", bsInstitute, "countryId")
cmbCountry.DataSource = bsCountry
cmbCountry.DisplayMember = "countryName"
cmbCountry.ValueMember = "countryId"
cmbCountry.DataBindings.Add(New Binding("SelectedValue", _
Me.bsInstitute, "countryId", True))
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Sub loadOptions()
Dim sql As String
Try
sqlConn = New SqlConnection(connString)
sqlConn.Open()
sql = "select instId, name, countryId from institute"
daInstitute = New SqlDataAdapter(sql, sqlConn)
daInstitute.Fill(dsOptions, "institute")
'----------------------------------------------------------------------
sql = "select countryId, countryName from country"
daAdapter = New SqlDataAdapter(sql, sqlConn)
daAdapter.Fill(dsOptions, "country")
'----------------------------------------------------------------------
sqlConn.Close()
Catch ex As Exception
sqlConn.Close()
MsgBox(Err.Description)
End Try
End Sub
Related
I'm trying to search a date using DateTimePicker in an Access database and have the results show in the DataGridView but it doesn't work. No errors but it just doesn't show the database/results. Here's pictures of the database and the debugged form when it doesn't work in case they are of any use:
and here's my code:
Imports System.Data.OleDb
Public Class Form10
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Sales.accdb;")
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dt1 As DateTime = DateTime.Parse(DateTimePicker1.Value)
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("MM/dd/yyyy"), connection)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
DataGridView2.DataSource = da
connection.Close()
End Sub
Private Sub Form10_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
End Class
Use the true date value of the datetime picker:
Dim dt1 As DateTime = DateTimePicker1.Value
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("yyyy'/'MM'/'dd") & "#", connection)
I have SQL QUERY:
SELECT T_DATA_LOG.ID, T_DATA_LOG.SerialNumber, T_DATA_LOG.Note, T_EVENT.Name
FROM T_DATA_LOG INNER JOIN T_EVENT ON T_DATA_LOG.ID_EVENT = T_EVENT.ID_EVENT;
Table T_DATA_EVENT is event catalog for T_DATA_LOG
I need update T_DATA_LOG.Note
I have this program. If I work directly with a spreadsheet, it works. if I use a query (join two tables) as a data source, it doesn't work.
Imports System.Data.OleDb
Public Class
Dim connetionString As String
Dim connection As OleDbConnection
Dim adapter As OleDbDataAdapter
Dim cmdBuilder As OleDbCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'connetionString = "Data Source=Server_Name\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "e:\tmp\KuKacka2.0.accdb;Persist Security Info=False;"
connection = New OleDbConnection(connetionString)
'sql = "Select * from D_DATA_LOG" - This is Work, but I need view data from T_EVENT
sql = "SELECT T_DATA_LOG.ID, T_DATA_LOG.SerialNumber, T_DATA_LOG.Note, T_EVENT.Name FROM T_DATA_LOG INNER JOIN T_EVENT ON T_DATA_LOG.ID_EVENT = T_EVENT.ID_EVENT;"
Try
connection.Open()
adapter = New OleDbDataAdapter(sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataGridView1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DataGridView1.Click
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New OleDbCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Please, give me an advice.
Thanks, David
I having some trouble. I have a datagridview that shown all the data from database sql server. But when i try to insert and save the new row one or multiple data in datagridview, the data from previous insert that shown in datagridview from database inserted again along with my new row data.
I just wanted to insert and save the new row data not along with my previous data.
Please help me!
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
cmd = New SqlCommand("Insert into DataSK values (#NIK, #Name, #Address, #Email, #Status)", con)
cmd.Parameters.Clear()
cmd.Parameters.Add("#NIK", SqlDbType.VarChar, 20).Value = dgv.Rows(row).Cells("NIK").Value
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = dgv.Rows(row).Cells("Name").Value
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 50).Value = dgv.Rows(row).Cells("Address").Value
cmd.Parameters.Add("#Email", SqlDbType.Char, 50).Value = dgv.Rows(row).Cells("Email").Value
cmd.Parameters.Add("#Status", SqlDbType.VarChar, 10).Value = dgv.Rows(row).Cells("Status").Value
cmd.ExecuteNonQuery()
End Sub
Something like this should get you going.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=YourDatabaseName;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Products"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
This should be straight forward but it doesn't want to work for me..
I'm trying to populate a Datagridview on form load. The Sub below works fine if i call Populategrid() from a button once the grid is populate with the Reloadrecords & displayrecords.
Public Sub populategrid()
If Trim(Me.Text) = "CIMDETAILS" Then
da = New SqlDataAdapter("SELECT * from Interactions where [Name] like '" & txtdetect2.Text & "%' order by [IntDate] desc", SQLCon)
dsetAssets = New DataSet
da.Fill(dsetAssets, "Interactions")
dgvData.DataSource = dsetAssets.Tables("Interactions").DefaultView
Else
ReloadRecords()
DisplayRecords()
End If
Public Sub DisplayRecords()
Try
Dim da = New SqlDataAdapter("SELECT * from Interactions order by [IntDate] desc", SQLCon)
dsetAssets = New DataSet
da.Fill(dsetAssets, "Interactions")
dgvData.DataSource = dsetAssets.Tables("Interactions").DefaultView
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub
Sub ReloadRecords()
Try
FillCIM("SELECT * FROM Interactions order by [IntDate] desc", dgvData)
dgvData.Columns(0).Visible = False
dgvData.Columns(1).Width = 300 ''Name''
dgvData.Columns(1).HeaderCell.Value = "Customer Name"
dgvData.Columns(2).Width = 200 ''Int type''
dgvData.Columns(2).HeaderCell.Value = "Interaction Type"
dgvData.Columns(3).Width = 170 ''Int Date''
dgvData.Columns(3).HeaderCell.Value = "Interaction Date"
dgvData.Columns(4).Width = 400 ''Remarks''
dgvData.Columns(4).HeaderCell.Value = "Remarks"
dgvData.Columns(5).Visible = False
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub
Private Sub CIMDETAILS_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReloadRecords()
DisplayRecords()
Call populategrid()
End Sub
Public Function FillCIM(ByVal Sqlstring As String, ByVal MyDataGrid As DataGridView)
Dim Constring = "Data Source=" & database & "\SQLEXPRESS; Initial Catalog = CIM; Integrated Security=true"
Dim SQLCon As New SqlConnection(Constring)
Dim SQLAdapter As New SqlDataAdapter()
Dim myDataset As New DataSet()
SQLCon.Open()
Try
SQLAdapter.SelectCommand = New SqlCommand(Sqlstring, SQLCon)
SQLAdapter.Fill(myDataset)
MyDataGrid.DataSource = myDataset.Tables(0)
Catch ex As Exception
End Try
SQLCon.Close()
SQLAdapter.Dispose()
myDataset.Dispose()
Return True
End Function
Pretty simple to get this working.
I've only just discovered there's an event after form load, which is form shown. Once i put the populategrid() sub in there it works fine.
Good evening.
I want to insert data to a table in SQL DB.I have a combo box with the values "5" and "6". When you click one or the other in the combo box i want these values to be inserted in a database( MS SQL Server 2008).I also have some textboxes which are bind correnctly and have no problem. The problem is with the bindings(i guess) of the combo box. I get sql exception.
Here is a snippet. Any help would be appreciated.Thanks
Private Sub BindFields()
txtSurname.DataBindings.Add("Text", ObjDataView, "surname")
txtName.DataBindings.Add("Text", ObjDataView, "name")
cboColor.DataBindings.Add(cboColor.SelectedValue.ToString, ObjDataView, "color")
End Sub
Private Sub Customers_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cboColor.Items.Add("5")
cboColor.Items.Add("6")
FillDataSetAndView()
BindFields()
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim objCommand As SqlCommand = New SqlCommand()
Dim intPosition As Integer
intPosition = objCurrencyManager.Position
ObjConnection.Open()
objCommand.Connection = ObjConnection
objCommand.CommandText = "INSERT INTO tblCustomers" & "(name, surname, color)" & "VALUES(#name,#surname,#color);"
objCommand.Parameters.AddWithValue("#name", txtName.Text)
objCommand.Parameters.AddWithValue("#surname", txtSurname.Text)
objCommand.Parameters.AddWithValue("#color", cboColor.SelectedValue.ToString)
Try
objCommand.ExecuteNonQuery()
Catch SqlExceptionErr As SqlException
MessageBox.Show(SqlExceptionErr.Message)
End Try
ObjConnection.Close()
FillDataSetAndView()
BindFields()
objCurrencyManager.Position = intPosition
ShowPosition()
End Sub
Inspect the cboColor.SelectedValue; it is not initialized and set to nothing. Attempting to call ToString on .SelectedValue will generate a Null Reference exception. I believe what you want is the cboColor.Text property; this will pull whatever the current text of whatever value the combobox is currently displaying.
For Example in C# :
if (comboBox1.SelectedItem != null)
{
SqlConnection con = new SqlConnection(Class1.str);
con.Open();
string query= "Insert Into Ex(Combo)Values ('" + comboBox1.SelectedItem + "' )";
SqlCommand com = new SqlCommand(query, con);
com.ExecuteNonQuery();
con.Close();
}