Binding Source Filter not working in DGV - vb.net

I'm having a problem with the binding source on a DGV . The message is "DataMember Property 'nodes' cannot be found on the dataSource " The column count is 14 after setting the table to the datasource. The error occurs on the line nodesDataGridView.DataSource = bsNodes. If I break before the error and then hover on the ds it does show that table nodes is in the datasource. I've used code similiar to this to setup other DGV's and I don't see any difference in this one.
if I remove these statements, I don't get the error but of course it is not filtered):
nodesDataGridView.DataSource = bsNodes
bsNodes.Filter = "company_number = " & Globals.customer_id
I should probably mention that I added company_number after the grid was completed and working. It was setup for a single company code but now I'm having to add the requirement to support multiple companies in the database.
Any ideas?
Thanks,
Vic
' Setup objects for loading the summary grid
Dim sqlNodes As String = "Select *From nodes order by display_sequence"
Dim comm As MySqlCommand = New MySqlCommand(sqlNodes, m_cn1)
Dim daNodes As MySqlDataAdapter = New MySqlDataAdapter(comm)
Dim dsNodes As DataSet = New DataSet()
dim bsNodes As New BindingSource
Try
AddHandler ButtonSaveChanges.Click, AddressOf ButtonSaveChanges_Click
dsNodes.Clear()
daNodes.Fill(dsNodes, "nodes")
m_cn1.Close()
nodesDataGridView.DataSource = dsNodes
nodesDataGridView.DataMember = "nodes"
bsNodes.DataSource = dsNodes.Tables("nodes")
Debug.Print("nodes column count is " & nodesDataGridView.ColumnCount)
nodesDataGridView.DataSource = bsNodes
bsNodes.Filter = "company_number = " & Globals.customer_id
Catch ex As Exception
MessageBox.Show("Failed to load summary grid" & vbCrLf & vbCrLf & ex.ToString)
End Try

try to filter like this
bsNodes.Filter = "company_number = '" & Globals.customer_id.ToString() & "'"
EDIT:
bsNodes.DataSource = dsNodes.Tables("nodes")
nodesDataGridView.DataSource = bsNodes '<- you set dsNodes(Dataset) this should be the BindingSource not Dataset
nodesDataGridView.DataMember = "nodes"
Debug.Print("nodes column count is " & nodesDataGridView.ColumnCount)
'nodesDataGridView.DataSource = bsNodes
bsNodes.Filter = "company_number = '" & Globals.customer_id.ToString() & "'"

Related

VB.net Update MS Access from DataGridView with BindingSource

I have a DataGridView populated with a SQL statement that users can input data on certain columns:
Me.bndDataGrid.DataSource = GetData("SELECT H.InnCode, R.RSRM, " & strCols & " E.Escalation " & _
"FROM (((dbo_HotelInfo AS H " & _
"INNER JOIN dbo_RSRM AS R ON H.RevMgr = R.ID) " & _
"INNER JOIN dbo_SrMgr AS S ON R.SrMgr = S.ID) " & _
"INNER JOIN " & strHitList & " AS L ON H.FacilityID = L.FacilityID) " & _
"INNER JOIN dbo_Escalation AS E ON H.FacilityID = E.FacilityID " & _
"WHERE S.ID = " & cbxSrMgr.SelectedValue.ToString)
With Me.grdQueryResults
.AutoGenerateColumns = True
.DataSource = bndDataGrid
End With
bndDataGrid is the BindingSource for grdQueryResults, the DataGridView. The code for GetData is commonly found on MS forums:
Private Shared Function GetData(ByVal sqlCommand As String) As DataTable
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source={MS Access DB Path Here};"
Dim ctnHitList As OleDbConnection = New OleDbConnection(strConn)
Dim tblHitList As New DataTable
Dim cmdHitList As New OleDbCommand(sqlCommand, ctnHitList)
Dim adrHitList As OleDbDataAdapter = New OleDbDataAdapter()
adrHitList.SelectCommand = cmdHitList
tblHitList.Locale = System.Globalization.CultureInfo.InvariantCulture
adrHitList.Fill(tblHitList)
Return tblHitList
End Function
Now once users are ready to save changes I can't for the life of me figure out how to have this save correctly, mostly since the data source for the DataGridView isn't simply bound to a table.
EDIT:
OK, so I mostly overhauled my code in accordance with Crowcoder's blog page, and got a lot further with it, but now on updating I'm running into a "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records" exception. Here's the update code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim parInnCode As OleDbParameter = New OleDbParameter("#parInnCode", OleDbType.WChar)
Dim parNotes As OleDbParameter = New OleDbParameter("#parNotes", OleDbType.WChar)
parInnCode.SourceColumn = "InnCode"
parNotes.SourceColumn = "Notes"
Using ctnDataGrid As New OleDbConnection(getConnectionString())
Using cmdGrid As New OleDbCommand("UPDATE (dbo_The400 AS T INNER JOIN dbo_HotelInfo AS H ON T.FacilityID = H.FacilityID) " & _
"INNER JOIN dbo_RSRM AS R ON H.RevMgr = R.ID " & _
"SET [Notes] = #parNotes WHERE H.InnCode = #parInnCode", ctnDataGrid)
Using adrDataGrid As New OleDbDataAdapter()
With adrDataGrid
.UpdateCommand = cmdGrid
With .UpdateCommand.Parameters()
.Add(parInnCode)
.Add(parNotes)
End With
grdQueryResults.EndEdit()
.Update(tblDataGrid)
End With
End Using
End Using
End Using
End Sub
tblDataGrid is declared at the Form Class level, wondering if that may be the issue or if my update query doesn't match the number of columns in the table? Or something else? Can't seem to find the right answer for my case :/
Welp, at long last I figured it out. It involved quite a bit of back end reorganizing to make it easier to connect to it via the front end .net application. Basically I threw all manager inputs into one table and added a column that corresponds to the initiative that required their input.
From there, I could build just about everything in the Dataset Designer and set the Update command on that tableadapter to just update that one table. Cut down the code on the main form to just a few lines that fill the datasources for the combobox columns in the datagridview.
Not an elegant coding solution, but it works!

Report only shows the last record

I have to display data from VB.NET code to crystal report...and I'm doing everything from the code, so the problem is that I have to display multiple data from for-each loop, this is the code:
Private Sub Print_Row(ByVal pp As Boolean)
Dim rptDokument As New ReportDocument, brkop As Integer
Dim rw_mat As DataRow
Dim cn As OracleClient.OracleConnection = New OracleClient.OracleConnection(Gdb_conn)
' Objects used to set the parameters in the report
Dim pCollection As New CrystalDecisions.Shared.ParameterValues
Dim pTSJ As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pNaziv As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pKolicina As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pTezina As New CrystalDecisions.Shared.ParameterDiscreteValue
Try
rptDokument.Load(Gpath & "PakLista.rpt")
pTSJ.Value = barcode.Text
pCollection.Add(pTSJ)
rptDokument.DataDefinition.ParameterFields("pTSJ").ApplyCurrentValues(pCollection)
cn.Open()
Dim myQuery As String = "SELECT S.TSJ,M.NAZ_MAT, S.IBRMAT, S.KOLICINA, S.TEZINA " & _
"FROM TWM_SADRZAJ S, TWM_MATER M, TWM_ATRIBUT A, TWM_PAKIR PAK " & _
"WHERE(S.VLASNIK_MP = M.VLASNIK_MP) " & _
"AND S.IBRMAT = M.IBRMAT " & _
"AND S.ATR_ID = A.ATR_ID (+) " & _
"AND PAK.VLASNIK_MP (+) = S.VLASNIK_MP " & _
"AND PAK.IBRMAT (+) = S.IBRMAT " & _
"AND PAK.PAK (+) = S.PAK " & _
"AND (S.TSJ = '" & barcode.Text & "') " & _
"ORDER BY S.IBRMAT"
Dim da As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(myQuery, cn)
Dim ds As New DataSet
da.Fill(ds, "TWM_SADRZAJ")
For Each rw_mat In ds.Tables("TWM_SADRZAJ").Rows
If (rw_mat.Item("NAZ_MAT") Is DBNull.Value) Then
pNaziv.Value = ""
Else
pNaziv.Value = CStr(rw_mat.Item("NAZ_MAT"))
End If
If (rw_mat.Item("KOLICINA") Is DBNull.Value) Then
pKolicina.Value = ""
Else
pKolicina.Value = CStr(rw_mat.Item("KOLICINA"))
End If
If (rw_mat.Item("TEZINA") Is DBNull.Value) Then
pTezina.Value = ""
Else
pTezina.Value = CStr(rw_mat.Item("TEZINA"))
End If
pCollection.Add(pNaziv)
rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina)
rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina)
rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
Next rw_mat
If pp Then
Dim frm As New frmPrint_preview
frm.crvDocument.ReportSource = rptDokument
frm.ShowDialog()
Else
Dim pd As New PrintDialog
pd.PrinterSettings = New PrinterSettings
If pd.ShowDialog(Me) Then
For brkop = 1 To pd.PrinterSettings.Copies
rptDokument.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName
rptDokument.PrintToPrinter(1, False, 1, 99999)
Next brkop
End If
End If
Catch Exp As LoadSaveReportException
MsgBox("Incorrect path for loading report.", MsgBoxStyle.Critical, "Load Report Error")
Catch Exp As System.Exception
MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The problem is in this section:
pCollection.Add(pNaziv) rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina) rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina) rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
It has to be out side for each loop to gather all the data, but the problem is no mater where i put this code it only displays the last record from data row for let's say 5 records in crystal report...I know it's peace of cake but I'm relay stuck here so I would appreciate a little help.
It is normal that the report only shows the last record, because you try to pass the data as parameters. Instead you should set the datasource programmatically, you can see how to do it here ^
ReportDocument.SetDataSource Method
and here you can find a complete example of how to create a typed dataset to use on your report
Create report by vb.net and crystal report

while saving from data gridview the same thing getting saved multiple times in vb.net application

I have a grid view like this: i am working on vb.net windows application
in load event i given code like this:
Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter = New SqlDataAdapter("select c.cid,c.CompanyName as Company,d.dtId,d.dtName as Department,d.dtPhone as D.phone,d.dtEmail as D.mail from CompanyMaster_tbl c join DepartmentMaster_tbl d on c.Cid=d.cId", con.connect)
dt1 = New DataTable
bSource = New BindingSource
adapter.Fill(dt1) 'Filling dt with the information from the DB
bSource.DataSource = dt1
gv.DataSource = bSource
gv.Columns("cid").Visible = False
gv.Columns("dtId").Visible = False
in save button i given code like this:
Dim sqlInsertT1 As String = ""
Dim sqlInsertT2 As String = ""
For i As Integer = 0 To gv.RowCount - 2
If gv.Rows(i).Cells(1).Value IsNot System.DBNull.Value Then
sqlInsertT1 = "Insert Into CompanyMaster_tbl(CompanyName) Values ('" + gv.Rows(i).Cells(1).Value + "')"
Exetransaction(sqlInsertT1)
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
End If
sqlInsertT2 = "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" + gv.Rows(i).Cells(3).Value + "','" + gv.Rows(i).Cells(4).Value + "','" + gv.Rows(i).Cells(5).Value + "'," & Ccid & ");"
Exetransaction(sqlInsertT2)
Next
in this case firs I added three department under the company IBS,then i saved.first time everything saved correct. again i run the application,and added one more department,phone,mail under the comapny IBS. then i clicked save button..but again the same department getting saved.. ( i dont want save all department again,i only want to save last added department,phone,email) ..so what i have to change in my code
As you have bound to dt1 in you given code you can look at dt1.GetChanges() to look at just what has changed if this is what you are after.
Alternatively I would suggest making the DataGrid read only and then have a new form for editing or adding a Department or Company. This gives far greater control but is only an option if you are in a position to make the DataGrid read only.

How to Trigger Code with ComboBox Change Event

I have a created a database containing historical stock prices. On my form I have two comboboxes, ComboBox_Ticker and ComboBox_Date. When these comboboxes are filled I want to check the database and see if the respective data exists in the database. If it does I want to change the text of a label called Label_If_Present to "In Database".
My problem occurs with the change event. I want all of this to happen once I change the data in the textboxes. I have tried both the .TextChanged and .LostFocus events. The '.TextChanged' triggers the code to early and throws and error in my SQL command statement. The `.LostFocus' event doesn't do trigger my code at all.
Here is my current code:
Public databaseName As String = "G:\Programming\Nordeen Investing 3\NI3 Database.mdb"
Public con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & databaseName)
Public tblName As String = "Historical_Stock_Prices"
Private Sub Change_Labels(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox_Ticker.TextChanged, ComboBox_Date.TextChanged
con.Close()
Dim dr As OleDbDataReader
con.Open()
If (File.Exists(databaseName)) Then
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = con.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
Else
Dim cmd2 As New OleDb.OleDbCommand("SELECT * FROM " & tblName & " WHERE Ticker = '" & ComboBox_Ticker.Text & "' " & " AND Date1 = '" & ComboBox_Date.Text & "'", con)
dr = cmd2.ExecuteReader
If dr.Read() = 0 Then
'If record does not exist
Label_If_Present.Text = ""
Else
Label_If_Present.Text = "In Database"
End If
con.Close()
End If
Else
End If
End Sub
I have successfully implemented this concept on other forms within my project. This one is slightly different and I can't figure out why I can't get this one to work.
Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value.
Then check to see that both comboboxes have values selected. Something like this should work:
If ComboBox_Ticker.Text <> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then

too slow in show report in vb.net 2010 using crytal report

I am using this code to show the report
Dim rpt As New CrystalReport1()
Dim sql As String
Dim where As String
If con Is Nothing OrElse con.State = ConnectionState.Closed Then
'MsgBox("closed")
OpenCon()
End If
Dim m As String
m = ""
For Each n As TreeNode In GetCheck(TreeView1.Nodes)
If n.Tag = 1 Then
m = m
Else
If m = "" Then
m = (n.Tag)
Else
m = m & ", " & (n.Tag)
End If
End If
Next
sql = "SELECT [bran_id],[f01],[f02],[f03],[f04],[f05],[f06],[f07],[f08],[bran_name],[comp_id],[comp_name],'" & dtStart.Value.Date & "' AS start_date, '" & dtEnd.Value.Date & "' AS end_date FROM [v_complain]"
If m = "" Then
MsgBox("لم يتم تحديد اى مدينة من فضلك قم بالاختيار اولا")
Exit Sub
Else
where = " WHERE bran_id in (" & m & ") and f02 between CONVERT(date,'" & dtStart.Value.Date & "',103) and CONVERT(date,'" & dtEnd.Value.Date & "',103)"
sql = sql + where
If cbF06.Checked = True Then
where = " AND (f06 like N'') or (f06 is null)"
sql = sql + where
End If
If cbF07.Checked = True Then
where = " AND (f07 like N'') or (f07 is null)"
sql = sql + where
End If
Dim dscmd As New SqlDataAdapter(sql, con)
Dim ds As New DataTable
dscmd.Fill(ds)
rpt.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rpt
CrystalReportViewer1.Refresh()
End If
con.Close()
but it's too slow to show the report in the first time. When I try to run it again without closing the window it work perfectly. Is there any way to make it faster?
Thanks
How slow it is? Several seconds?
I believe it happens do to a need to initialize underling reports 'engine'. I had similar issues and the best I could come up with was to display "Creating report, please wait..." message to a user so they. As an alternative, when you start your app, you can make a 'fake' call to create a dummy report in the background without displaying anything to a user so all required resources will be initialized by the time user is ready to create a real report.