Updating a table from a Form DGV - vb.net

I have a DGV which loads from a stored procedure in my application:
Dim conn As New SqlConnection(My.Resources.FCLRptConn)
Dim cmd As New SqlCommand("spFCLEditAgentAssignments", conn)
cmd.CommandType = CommandType.StoredProcedure
Dim ds As New DataSet
Dim DA As New SqlDataAdapter(cmd)
cmd.Parameters.AddWithValue("#ActiveIndicator", Me.tscmbActiveIndicator.ComboBox.SelectedValue)
DA.Fill(ds)
Me.dgvAgentAssignment.DataSource = ds.Tables(0)
Before this I added a DataGridViewComboBox column that binds to one of the columns in the DGV:
Dim conn As New SqlConnection(My.Resources.FCLRptConn)
Dim cmd As New SqlCommand("spFCLLUVTeamAssignment", conn)
Dim da As New SqlDataAdapter(cmd)
Dim TeamAssign As New DataTable
da.Fill(TeamAssign)
With FCLTeam
.DataPropertyName = "FCLTeamID"
.Name = "FCLTeamID"
.DataSource = TeamAssign
.DisplayMember = "FCLTeamName"
.ValueMember = "FCLTeamID"
.AutoSizeMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
End With
When the table is loaded I come up with an
"Object reference not set to an instance of an object" error. This occurs in this block of code:
cmd.CommandText = "UPDATE tblFCLAgentAssignment SET [" & ColumnName & "] = '" & _
ConvertVBBooleanToSQLBit(dgvAgentAssignment.CurrentRow.Cells(ColumnName).Value) & _
"' WHERE RefID = '" & dgvAgentAssignment.CurrentRow.Cells("RefID").Value & "'"
The above code is used to update fields or cells that are updated through the DGV.
After I skip past the error I can updated the 'FCLTeamID' field with no issues. What could I be doing wrong on load?

If Not String.IsNullOrEmpty(ColumnName) Then
cmd.CommandText = "UPDATE tblFCLAgentAssignment SET [" & ColumnName & "] = '" & _
ConvertVBBooleanToSQLBit(dgvAgentAssignment.CurrentRow.Cells(ColumnName).Value) & _
"' WHERE RefID = '" & dgvAgentAssignment.CurrentRow.Cells("RefID").Value & "'"
End If
This took care of the ColumnName issue where if it was empty it would not try to update the table

Related

SSIS Create and Attaching file to the email

I've 2 sqlreaders and both should loop through it and second sqlreader data should create a table and inserting into the excel sheet.
Lets say
I've sqlreader and sqlreader1
sqlreader has some data which is required to get sqlreader1
I'm able to get sqlreader1 data as I expected
but once I loaded data to datatable, I'm loosing sqlreader1 and not able to see any info in sqlreader1
If SqlDataReader.HasRows Then
Do While SqlDataReader.Read()
Dim ExcelFileName As String = Dts.Variables("User::FolderPath").Value.ToString() + "Accrual_Input_Summary_Q" + SqlDataReader.Item("Accrual_Quarter").ToString() + " FY-" + SqlDataReader.Item("Accrual_FY").ToString() + ".xlsx"
'Dim recipientName As String = SqlDataReader.Item("recipient_name").ToString()
'Dim recipientEmail As String = SqlDataReader.Item("Recipient_Email").ToString()
Try
If System.IO.File.Exists(ExcelFileName) = True Then
System.IO.File.Delete(ExcelFileName)
End If
Dim SqlCmd1 As New SqlCommand("[POT].[PROC_POT_Accrual_Reminder_Summary]", SqlCon)
SqlCmd1.CommandType = CommandType.StoredProcedure
SqlCmd1.CommandTimeout = 0
SqlCmd1.Parameters.AddWithValue("#Qtype", "Accrual_Summary")
SqlCmd1.Parameters.AddWithValue("#Accrual_Created_By_Email", SqlDataReader.Item("Recipient_Email").ToString())
Dim SqlDataReader1 As SqlDataReader = SqlCmd1.ExecuteReader()
' connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" &
'"Data Source=" & ExcelFileName &
'";Extended Properties=Excel 12.0 Xml;HDR=YES;"
If SqlDataReader1.HasRows Then
While SqlDataReader1.Read()
Dim connectionString As String
Dim excelConnection As OleDbConnection
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & ExcelFileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"""
excelConnection = New OleDbConnection(connectionString)
Dim Excel_OLE_Cmd As OleDbCommand = New OleDbCommand()
Dim recipientName As String = SqlDataReader1.Item("Created_By_Name").ToString()
Dim recipientEmail As String = SqlDataReader1.Item("CostCenterAnalyst").ToString()
Dim costCenterOwner As String = SqlDataReader1.Item("CostCenterOwner").ToString()
Dim TableColumns As String = ""
Dim dtCustomers As New DataTable("sqlDataTable")
**dtCustomers.Load(SqlDataReader1)**
For Each column As DataColumn In dtCustomers.Columns
TableColumns += column.ToString() & "],["
Next
TableColumns = ("[" & TableColumns.Replace(",", " Text,").TrimEnd(","c))
TableColumns = TableColumns.Remove(TableColumns.Length - 2)
excelConnection.ConnectionString = connectionString
excelConnection.Open()
Excel_OLE_Cmd.Connection = excelConnection
Excel_OLE_Cmd.CommandText = "Create table " & "Sheet1" & " (" & TableColumns & ")"
Excel_OLE_Cmd.ExecuteNonQuery()
Dim sqlCommandInsert As String = ""
Dim sqlCommandValue As String = ""
For Each dataColumn As DataColumn In dtCustomers.Columns
sqlCommandValue += dataColumn.ToString() & "],["
Next
sqlCommandValue = "[" & sqlCommandValue.TrimEnd(","c)
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2)
sqlCommandInsert = "INSERT into " & "Sheet1" & "(" & sqlCommandValue & ") VALUES("
Dim columnCount As Integer = dtCustomers.Columns.Count
For Each row As DataRow In dtCustomers.Rows
Dim columnvalues As String = ""
For i As Integer = 0 To columnCount - 1
Dim index As Integer = dtCustomers.Rows.IndexOf(row)
columnvalues += "'" & dtCustomers.Rows(index).ItemArray(i).ToString() & "',"
Next
columnvalues = columnvalues.TrimEnd(","c)
Dim command As String = sqlCommandInsert & columnvalues & ")"
Excel_OLE_Cmd.CommandText = command
Excel_OLE_Cmd.ExecuteNonQuery()
Next
excelConnection.Close()
StrMailBody_Inner = " Hello Cost Center Analyst (" & recipientName & "), <br/><br/> PFA accrual inputs for the current quarter. Please review & take appropriate action click <a href='http://podashboarddev/' target='_blank'>here</a>.<br/><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <u>Note</u><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <ol>"
StrMailBody_Inner = StrMailBody_Inner + " <li>The accrual inputs provided doesn't interface with SAP. You will still need to post the necessary accrual JV.</li>"
StrMailBody_Inner = StrMailBody_Inner + " <li>CCA can leverage the tool for accrual tracking.</li>"
StrMailBody_Inner = StrMailBody_Inner + " </ol>"
Using myMessage As New MailMessage(Dts.Variables("email_from").Value, recipientEmail)
Dim copy As MailAddress = New MailAddress(costCenterOwner)
myMessage.CC.Add(copy)
myMessage.IsBodyHtml = True
myMessage.Subject = Dts.Variables("email_subject").Value
myMessage.Body = StrMailBody.ToString().Replace("$$$$Mail_Body$$$$", StrMailBody_Inner)
myMessage.Priority = System.Net.Mail.MailPriority.High
myMessage.Attachments.Add(New Attachment(ExcelFileName))
mySmtpClient = New SmtpClient("mailserver.amat.com")
mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
'mySmtpClient.Send(myMessage)
Dim str_SQL As String
str_SQL = "INSERT INTO [POT].[tbl_POT_Open_PO_Accrual_Reminder_History] ([Recipient_Email], [Reminder_Type]) VALUES ('" + SqlDataReader.Item("recipient_email").ToString() + "', 'Accrual_Summary');"
Dim SqlCmdHist As New SqlCommand(str_SQL, SqlCon)
SqlCmdHist.CommandType = CommandType.Text
SqlCmdHist.CommandTimeout = 0
SqlCmdHist.ExecuteNonQuery()
SqlCmdHist.Dispose()
End Using
End While
SqlDataReader1.Close()
End If
Once I load data to Datatable using this
dtCustomers.Load(SqlDataReader1)
before load data:
after load data:
I'm missing the sqlreader1 and i'm unable to loop through it.
it is giving Invalid attempt to call Read when reader is closed.
Note: I've enabled MultipleActiveResultSets
can we do any other things that we can do to resolve this issue

Pass a value dynamically to SQL Server through VBA

Disclaimer: I am new to VBA.
I hope to pass the value in the SQL query (30881570) through a field on my Excel sheet. I have tried a few different things.
Private Sub cmdImport_Click()
Call cmdClear_Click
Dim conn As New ADODB.Connection, cmd As New ADODB.Command, rs As New ADODB.Recordset
With conn
.ConnectionString = _
"Provider=SQLOLEDB; " & _
"Data Source=PRGTAPPDBSWC019; " & _
"Initial Catalog=DETEP;" & _
"Integrated Security=SSPI;"
.Open
End With
With cmd
.ActiveConnection = conn
.CommandText = "SELECT * FROM [dbo].[tbl_PMHeader] WHERE [PMHeader_PM_NUM] = '30881570'"
.CommandType = adCmdText
End With
Set rs.Source = cmd
rs.Open
'Need this to populate header row, starting at specified Range
For intColIndex = 0 To rs.Fields.Count - 1
Range("B1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
'This is where your data table will be copied to
ActiveSheet.Range("B2").CopyFromRecordset rs
Worksheets("Sheet1").Columns("B:BB").AutoFit
Worksheets("Sheet1").Range("A25").Formula = "=COUNTA(B:B)-1"
End Sub
It looks like you're already passing that value as criteria for the query's WHERE statement.
If you're asking how to replace that with a value from a worksheet, here's one way:
.CommandText = "SELECT * FROM [dbo].[tbl_PMHeader] " & _
"WHERE [PMHeader_PM_NUM] = '" & Sheets("mySheet").Range("A1") & "'"
...where your worksheet is named mySheet and the value is in cell A1.
This is the simplest method, potentially fine for internal use by trusted parties, but if the value has any ' single-quotes in it, you will get an error.
Worst-case scenario, this method leaves you open to SQL Injection attacks. Depends on your needs (and whether this this is just a school assignment), you may be better of using a parameter query.
See Also:
MSDN Blog : How and Why to Use Parameterized Queries
MSDN Blog : Everything About Using Parameters from Code
Private Sub cmdImport_Click()
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim sqlStr As String
With conn
.ConnectionString = _
"Provider=SQLOLEDB; " & _
"Data Source=PRGTAPPDBSWC019; " & _
"Initial Catalog=DETEP;" & _
"Integrated Security=SSPI;"
.Open
End With
orderno = Sheets("Sheet1").Range("A22")
strSql = "SELECT * FROM [dbo].[tbl_PMHeader] " & _
"WHERE [PMHeader_PM_NUM] = " & orderno
With cmd
.ActiveConnection = conn
.CommandText = strSql
.CommandType = adCmdText
End With
'Call cmdClear_Click
Set rs.Source = cmd
rs.Open
'Need this to populate header row, starting at specified Range
For intColIndex = 0 To rs.Fields.Count - 1
Range("B1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
'This is where your data table will be copied to
ActiveSheet.Range("B2").CopyFromRecordset rs
Worksheets("Sheet1").Columns("B:BB").AutoFit
Worksheets("Sheet1").Range("A25").Formula = "=COUNTA(B:B)-1"
End Sub

MS Access Textbox Default Value Max Size Limit

I have the following setup:
I have a form with unbound textbox controls. I have a procedure that fires after every AfterUpdate event.
The procedure sends the input value to a table and returns the value input in the table as the textbox's DefaultValue. The table defines unique rows by the form and control name, 2 primary keys.
After data is input, there is a button that sends data from the form in a structured way to another table and a report reads off the table. The data is input into the table in a structured way with an SQL query.
The problem is when a user inputs texts over 2048 characters in two of the fields, the code breaks due to the limit. Two of the fields on the form, on each page will likely have over 2k characters due to the nature of the forms.
My question is, can I circumvent, increase or bypass the character limit?
My code is posted below for reference if needed (Procedure called OptimizeS is loaded in every textbox on the form):
Procedure that writes the input value to the table:
Private Sub OptimizeS()
Dim cmd As ADODB.Command
Dim strForm As String
Dim strControl As String
Dim strSQL As String
Dim strCriteria As String
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strCriteria = "FormName = """ & Me.Name & """ " & _
"And ControlName = """ & Me.ActiveControl.Name & """"
' is there an existing default for this control?
If Not IsNull(DLookup("FormName", "Defaults", strCriteria)) Then
' if so then update row in table
strSQL = "UPDATE Defaults " & _
"SET DefaultVal = """ & Me.ActiveControl & """ " & _
"WHERE " & strCriteria
Else
' insert new row
strSQL = "INSERT INTO Defaults(" & _
"FormName,ControlName,DefaultVal) " & _
"VALUES(""" & Me.Name & """,""" & _
Me.ActiveControl.Name & """,""" & _
Me.ActiveControl & """)"
End If
cmd.CommandText = strSQL
cmd.Execute
End Sub
Support Procedures on the form itself:
1)
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim cmd As ADODB.Command
Dim strOpened As String
Dim strForm As String
Dim strSQL As String
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strOpened = "Opened = """ & Me.Name & """ "
If Not IsNull(DLookup("Opened", "AllOpened", strOpened)) Then
strSQL = "UPDATE AllOpened " & _
"SET Opened = """ & Me.Name & """ " & _
"WHERE " & strOpened
Else
strSQL = "INSERT INTO AllOpened(Opened) " & _
"VALUES(""" & Me.Name & """)"
End If
cmd.CommandText = strSQL
cmd.Execute
End Sub
2)
Private Sub Form_Open(Cancel As Integer)
Dim cmd As ADODB.Command
Dim strCriteria As String
Dim strOpened As String
Dim varDefault As Variant
Dim varOpened As Variant
Dim strForm As String
Dim strSQL As String
Dim ctrl As Control
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strOpened = "Opened = """ & Me.Name & """ "
varOpened = DLookup("Opened", "AllOpened", strOpened)
If IsNull(varOpened) Then
strSQL = "INSERT INTO AllOpened(Opened) " & _
"VALUES(""" & Me.Name & """)"
cmd.CommandText = strSQL
cmd.Execute
Else
GoTo ErrMsg
End If
For Each ctrl In Me.Controls
strCriteria = "FormName = """ & Me.Name & """ " & _
"And ControlName = """ & ctrl.Name & """"
varDefault = DLookup("DefaultVal", "Defaults", strCriteria)
If Not IsNull(varDefault) Then
ctrl.DefaultValue = """" & varDefault & """"
End If
Next ctrl
Exit Sub
ErrMsg:
MsgBox ("The form is already open by another user. Please double-check before editing."), , "Important!!!"
End Sub
3)
Private Sub Form_Unload(Cancel As Integer)
Dim strSQL As String
Dim strForm As String
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strSQL = "DELETE FROM AllOpened " & _
"WHERE Opened = """ & Me.Name & """"
cmd.CommandText = strSQL
cmd.Execute
End Sub
That's a hint in your last comment. Then try this verbose code using string variable that for sure doesn't have a 2K limit:
Dim DefaultString As String
DefaultString = Nz(varDefault)
ctrl.DefaultValue = DefaultString

VB.net Retrieving dataset values from a particular column into a string

I need to copy structure of selected database to a new database. How is it possible? I am not able to retrieve the DataSet value. I need to use this value to retrieve the table names associated with the database. Here is my code.
cmd.CommandText = "create database " & txtCustId.Text & "AAA"
cmd.ExecuteNonQuery()
Dim dtadapt As New SqlDataAdapter("select table_name from " & name & ".INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'", comm_con)
Dim dtset As New DataSet
dtadapt.Fill(dtset)
Dim dttb As DataTable = dtset.Tables(0)
'Dim row As Integer = 1
Dim arrS As String = ""
while dttb.Rows.Count > 0
'arrS =Convert.ToString(dtset.Tables[i].Rows[0]["table_name"])
arrS = dttb("table_name").ToString
cmd.CommandText = " SELECT * INTO " & txtCustId.Text & "AAA.dbo." & arrS & " FROM " & name & ".dbo." & arrS & " where 1=1"
cmd.ExecuteNonQuery()
'MessageBox.Show("done")
End while

Selecting Data from Excel Spreadsheet Doesn't get First Row

I'm using an OleDbDataReader to loop through my imported excel file and it gets everything in the file except for the first row. How can I specify that I want to see this header row?
strSQL = "SELECT * FROM [" & firstSheetName & "]"
Dim myCommand As New OleDbCommand(strSQL, myConnection)
Dim myDba As OleDbDataReader
myDba = myCommand.ExecuteReader
s = ""
While myDba.Read()
For i = 0 To myDba.FieldCount - 1
s &= myDba.Item(i) & vbTab
Next
s &= vbCrLf
End While
You should specify that your spreadsheet doesn't have header: HDR=No .