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

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

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

How to merge from multiple field of access database to one column fo datagridview in vb.net using dataset

How to convert recordset to dataset because while 200 more data load to datagridview that after datagrid has been very slow, so i want my code change to load datagrid by dataset but i dont know dataset code how to merge multiple field of database data into one column in datagrid, So please help me...
Private Sub FLEX1_LOAD()
DataGridView1.Rows.Clear()
Dim strsql As String
Dim rs2 As ADODB.Recordset
strsql = "select * from voterlist where AREAID='" & Trim(lblAreaid.Text) & "'"
rs2 = New ADODB.Recordset
Call dbconnect2()
rs2.Open(strsql,conne2,ADODB.CursorTypeEnum.adOpenStatic,ADODB.LockTypeEnum.adLockPessimistic)
If rs2.RecordCount > 0 Then
rs2.MoveFirst()
For I = 0 To rs2.RecordCount - 1
DataGridView1.Rows.Add(1)
DataGridView1.Rows(J).Cells(0).Value = J + 1
DataGridView1.Rows(J).Cells(1).Value =rs2.Fields("ID").Value
DataGridView1.Rows(J).Cells(2).Value = rs2.Fields("NAM").Value & " " & rs2.Fields("SURNAME").Value & "/" & rs2.Fields("RTYPE").Value & "-" & rs2.Fields("RNAME").Value & " " & rs2.Fields("RSURNAME").Value
DataGridView1.Rows(J).Cells(3).Value = rs2.Fields("AGE").Value
J = J + 1
rs2.MoveNext()
Next
End If
rs2.Close()
rs2 = Nothing
conne2.Close()
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

Updating a table from a Form DGV

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

sort two dimensional array by descending vb.net

Please could you help me sort this by 2nd column descending?
Dim ds As New DataSet()
conn.Open()
techSpeciality = LB_techFaultType.Text
techZone = LB_TechZone.Text
Dim strSQL As String = "SELECT Tech_ID, Last_Zone FROM Technician_List WHERE Availability=TRUE AND Speciality='" & techSpeciality & "' AND Last_Zone='" & techZone & "'"
Dim da As New OleDbDataAdapter(strSQL, conn)
da.Fill(ds)
'2D array
Dim values(ds.Tables(0).Rows.Count - 1, 2) As Integer
'for loop between 0 and all available technicians
For value As Integer = 0 To ds.Tables(0).Rows.Count - 1
'Tech_ID column
values(value, 0) = ds.Tables(0).Rows(value).Item(0).value()
'Zone column, converts negative value to a positive and minus' the selected techZone
Math.Abs(values(value, 1) = techZone - ds.Tables(0).Rows(value).Item(1).value())
Next
Modify this line:
Dim strSQL As String = "SELECT Tech_ID, Last_Zone" & _
" FROM Technician_List WHERE" & _
" Availability=TRUE AND Speciality='" & techSpeciality & _
"' AND Last_Zone='" & techZone & _
"' ORDER BY Last_Zone DESC"
For more information on the ORDER BY keywords:
http://www.w3schools.com/sql/sql_orderby.asp
Another option is to do ORDER BY 2 DESC, instead of directly specifying the column name.