How to find specific string and dynamic string - asp.net

How can I get the values in single quote from DescriptionMsg column which having the common string as 'Account Number is changed from'.
SELECT Logid, mrd_id, mrd_accountnumber, DescriptionMsg
FROM RecordData_Log
WHERE Log_date > '2020-12-31 23:59:59.999'
AND Log_type = 'Record Updated'
AND DescriptionMsg LIKE '%Account Number is changed from%';
Here is the sample output when I run the above sql query.
" Account Number is changed from '2' to '2121212121'.Logo is
changed. "
I need the values in single comma which is 2 and 2121212121 in this example. For multiple records how can I find it.

Not clear if you looking to process get this information in code, or from the query?
I mean, you can always parse out the value.
Say like this:
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"SELECT Logid, mrd_id, mrd_accountnumber, DescriptionMsg FROM RecordData_Log " &
"WHERE Log_date > '2020-12-31 23:59:59.999' AND Log_type = 'Record Updated' " &
"And DescriptionMsg LIKE '%Account Number is changed from%';"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim rstData = New DataTable
rstData.Load(cmdSQL.ExecuteReader)
For Each OneRow As DataRow In rstData.Rows
Dim str As String = OneRow("DescriptionMsg").ToString.Replace("'", "")
str = str.Split("from ")(1)
Dim strFromNumber As String = str.Split(" ")(1)
Dim strToNumber As String = str.Split(" ")(3)
strToNumber = strToNumber.Split(".")(0)
Debug.Print("From num = " & strFromNumber)
Debug.Print("To num = " & strToNumber)
Next
End Using
End Using
With your sample string, the output is:
From num = 2
To num = 2121212121

Related

Make a for each using SqlDataReader vb.net

i need store the value "IdMaterial" from table 1 ( imagine that have more that 40 records) into a array save all that reacord into table 2 on the code i will show you only save me the first record and not all.
i will apreceate your help i a noobie in proraming
Code :
Dim i As Integer
i = 0
Try
Dim mater As String
Dim planta As String
Dim almacen As String
Dim lot As String
Dim cantidad As String
Dim cantadiat As String
Dim undad As String
Dim Cantidadc As String
Dim CantidadB As String
Dim Session1 As String
Dim fecha As String
'''''
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Using CustCommand As New SqlCommand(editCustQuery, Con34)
Dim dr As SqlDataReader = CustCommand.ExecuteReader()
dr.Read()
mater = dr.GetString(0)
planta = dr.GetString(1)
almacen = dr.GetString(2)
lot = dr.GetString(3)
cantidad = dr.GetString(4)
cantadiat = dr.GetString(5)
undad = dr.GetString(6)
Cantidadc = dr.GetString(7)
CantidadB = dr.GetString(8)
Session1 = dr.GetString(9)
fecha = dr.GetDateTime(10)
end using
Dim Con As New Data.SqlClient.SqlConnection
Dim StrSQL As String
Con.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
StrSQL = ""
StrSQL = "EXEC P_AsigDupla '" & Txtfecha.Text & "','" & cboPlanta0.SelectedValue & "', '" & cboPlanta0.SelectedItem.Text & "','" & cboAlmacen.SelectedValue & "', '" & cboAlmacen.SelectedItem.Text & "', '" & mater & "', '" & lot & "'"
Con.Open()
Dim CmdAd As New Data.SqlClient.SqlCommand(StrSQL, Con)
CmdAd.ExecuteNonQuery()
Con.Close()
i = i + 1
'Next
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
First of all if I understand correctly, you want to put the information of those 40 rows and multiple columns into multiple arrays. If that is true then you are missing () when declaring the arrays.
Dim mater() As String
Dim planta() As String
Dim almacen() As String
Dim lot() As String
Dim cantidad() As String
Dim cantadiat() As String
Dim undad() As String
Dim Cantidadc() As String
Dim CantidadB() As String
Dim Session1() As String
Dim fecha() As String
Dim RowCounter as Integer = 0
Second I will approach this different. I will run the query and put the result into a DataTable. Then with a For go through each row and start filling the arrays.
MySQLOpenConnection()
Dim MySQLExecute As New MySqlCommand(MySQLCommand, MySQLConnection)
Dim MySQLAdapter As MySqlDataAdapter = New MySqlDataAdapter(MySQLExecute)
Dim TableResult As New DataTable("QueryResult")
MySQLAdapter.Fill(TableResult)
MySQLCloseConnection()
For each tablerow as DataRow in TableResult.Rows
mater(RowCounter) = TableResult.Rows.Item(RowCounter).Item(0)
planta(RowCounter) = TableResult.Rows.Item(RowCounter).Item(1)
almacen(RowCounter) = TableResult.Rows.Item(RowCounter).Item(2)
lot(RowCounter) = TableResult.Rows.Item(RowCounter).Item(3)
cantidad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(4)
cantadiat(RowCounter) = TableResult.Rows.Item(RowCounter).Item(5)
undad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(6)
Cantidadc(RowCounter) = TableResult.Rows.Item(RowCounter).Item(7)
CantidadB(RowCounter) = TableResult.Rows.Item(RowCounter).Item(8)
Session1(RowCounter) = TableResult.Rows.Item(RowCounter).Item(9)
fecha(RowCounter) = TableResult.Rows.Item(RowCounter).Item(10)
RowCounter=RowCounter+1
Next
The comment did not have enough characters for the answer for the second issue so here it goes.
Ok, I see you are using values from the array mater, and lot, but you have to define which one of the values inside the array.
mater() and lot() are as long as the amount of rows of the of the table in the database. So if you have 20 rows on that table, the array lot will have 20 elements going from lot(0) to lot(19) and the same for the others.
If you need to get resultado for each row, then you have to define resultado() as an array and use the same FOR to fill it.
resultado(RowCounter)=GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater(RowCounter), lot(RowCounter)
I hope this solve your issue.

Apply filters from multiple checkboxList to filter ListView in VB.net

I have webapplication where there are 1000 of products so there is multiple filter needs to be there. I have total 4 checkboxList. Now my problem is if I apply filter from any of checkboxList then it checks selected value for all column that is specified in query.
What I want is like below
SELECT * FROM products WHERE price_rang IN ('selectedValueFromCheckBoxList1') And category IN ('selectedValueFromCheckBoxList2')
What is happening now
SELECT * FROM `products` WHERE price_range IN ('selectedValueFromCheckBoxList2') AND category IN ('selectedValueFromCheckBoxList2')
So in this query suppose If I select value First from checkboxList2 then for both the columns it takes that value & result not displaying.
Below is my filter process code
Private Sub getResult()
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Dim query As String = "select * from products"
Dim condition As String = String.Empty
For Each price As ListItem In priceFilter.Items
condition += If(price.Selected, String.Format("'{0}',", price.Value), String.Empty)
Next
For Each sub_category As ListItem In category.Items
condition += If(sub_category.Selected, String.Format("'{0}',", sub_category.Value), String.Empty)
Next
If Not String.IsNullOrEmpty(condition) Then
condition = String.Format(" WHERE price_range IN ({0}) and sub_category IN ({0})", condition.Substring(0, condition.Length - 1))
End If
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(query & condition)
Using sda As New MySqlDataAdapter(cmd)
cmd.Connection = con
Using dt As New DataTable()
sda.Fill(dt)
products.DataSource = dt
products.DataBind()
End Using
End Using
End Using
End Using
End Sub
This is an option is you're only interested in the checked items.
Public Function buildWhereClause() As String
Dim query As String = "select * from products"
Dim joiner As String = " "
Dim condition As String = String.Empty
Dim priceCondition As String = String.Empty
For i = 0 To priceFilter.Items.Count - 1
If priceFilter.Items(i).Selected Then
Dim price As String = priceFilter.Items(i).ToString
priceCondition = String.Concat(priceCondition, joiner, String.Format("'{0}'", price))
If joiner = " " Then joiner = ", "
End If
Next
Dim categoryCondition As String = String.Empty
joiner = " "
For i = 0 To categoryFilter.Items.Count - 1
If categoryFilter.Items(i).Selected Then
Dim category As String = categoryFilter.Items(i).ToString
categoryCondition = String.Concat(categoryCondition, joiner, String.Format("'{0}'", category))
If joiner = " " Then joiner = ", "
End If
Next
Dim whereClause As String = String.Empty
joiner = " where "
If Not String.IsNullOrEmpty(priceCondition) Then
whereClause = String.Concat(whereClause, joiner, String.Format(" price_range IN ({0})", priceCondition)) ' and sub_category IN ({0})", condition.Substring(0, condition.Length - 1))
joiner = " and "
End If
If Not String.IsNullOrEmpty(categoryCondition) Then
whereClause = String.Concat(whereClause, joiner, String.Format(" sub_category in ({0})", categoryCondition))
joiner = " and "
End If
Return String.Concat(query, whereClause)
End Function

Validate that textbox has numeric value in vb.net and compare value with database

enter image description hereI'm trying to validate a textbox where users will put an ID. The ID has to be numeric and at the same time compare to a valid ID in the database. When I was just validating for numeric, I didn't have any problems. But now that I have two conditions, my code doesn't work properly. Whenever I type in letters in the textbox and click a button, it gives me an error. The boolean is throwing me off lol. Below is my code:
Thank you in advance.
Protected Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim dt As DataTable
Dim dr As DataRow
Dim Conn As New SqlConnection("Data Source=Computer;Initial Catalog=Catalog;Persist Security Info=True;User ID=userid;Password=password")
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value", Conn)
cmd.Parameters.Add("#Value", SqlDbType.NVarChar).Value = txtId.Text
Conn.Open()
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
Conn.Close()
If (IsNumeric(txtId.Text)) AndAlso valueExistsInDB = True AndAlso txtId.Text IsNot Nothing Then
dt = GetDataTable("SELECT ID, LEFT(SANZ_ID, PATINDEX('%.%', SANZ_ID) -1) AS City, CASE WHEN ST_DIR_ID = 1 THEN 'NB' WHEN ST_DIR_ID = 2 THEN 'SB' WHEN ST_DIR_ID = 3 THEN 'EB' WHEN ST_DIR_ID = 4 THEN 'WB' END AS ST_DIR, STREET_OF_TRAVEL, CROSS_STREET, (SELECT TOP 1 CASE WHEN STATUS_ID = 1 THEN 'F' WHEN STATUS_ID = 2 THEN 'P' WHEN STATUS_ID = 3 THEN 'I' WHEN STATUS_ID = 4 THEN 'N' WHEN STATUS_ID = 5 THEN 'A' END FROM tbl where dbo.tbl.ID=ID) AS STATUS FROM tbl WHERE ID=" & txtId.Text)
dr = dt.Rows(0)
labelStreet.Text = dr("street_of_travel")
labelCrossStreet.Text = dr("cross_street")
labelCity.Text = dr("city")
labelDir.Text = dr("st_dir")
labelAda.Text = dr("STATUS")
'dropdownStatus.SelectedValue=
dropdownStatus.Visible = True
txtNotes.Visible = True
btnSave.Visible = True
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End If
End Sub
If ID is a numeric field then you should pass a numeric parameter not an NVarChar one
' First try to convert the input text to an integer '
' this should be done here before acting on the db '
Dim id As Integer
if Not Int32.TryParse(txtId.Text, id) Then
MessageBox.Show("Error, not a valid number")
return
End If
Dim cmdText = "SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value"
Using Conn = New SqlConnection(....)
Using cmd As New SqlCommand(cmdText, Conn)
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = id
Conn.Open()
Dim valueExistsInDB = CBool(CInt(cmd.ExecuteScalar()) > 0)
' At this point you don't need anymore to check if the input value'
' is numeric and your if is more simple.....'
if valueExistsInDB Then
......
... continue with your code ....
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End if
End Using
End Using

Invalid attempt to read when no data is present error

I have a function whose sole purpose is to fetch some data when a button is pressed and it's called multiple times. This is the function code:
Function GetData2(ByVal clientNo As Integer) As List(Of SocioInfo)
Dim theResults2 = New List(Of SocioInfo)
Dim connStr = "Data Source=localhost;Initial Catalog=testdb;Integrated Security=True;MultipleActiveResultSets=true"
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [FirstName], [LastName] FROM [CustInfo] Where ([NumCuenta] = #SocioNum)"
Dim sql2 = "SELECT [AcctName], [AcctNum], [NewAcct], [Balance] From [ACCT_NEW] Where ([AcctNum] = #SocioNum)"
Dim sqlCmd = New SqlCommand(sql, conn)
Dim sqlCmd2 = New SqlCommand(sql2, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
sqlCmd2.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
Dim rdr2 = sqlCmd2.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
})
End While
While rdr2.Read
theResults2.Add(New SocioInfo With {
.CuentaName = rdr.GetString(0),
.AcctNum = rdr.GetValue(1),
.AcctFull = rdr2.GetValue(2),
.Balance = rdr2.GetValue(3)
})
End While
End Using
Return theResults2
End Function
I am not 100% sure if this is the best way to do this (basically need to get data from two different tables). Thing is, while Rdr shows me no error, Rdr2 just blows in the face. The exception is this:
Invalid attempt to read when no data is present.
In the second loop you are trying to use the first SqlDataReader but this is not possible because the first loop has already reached the end of the input data.
If you need joined data between the two tables a better approach is to use just one query using the JOIN operator. This query works assuming that each customer in the CustInfo table has one account in the ACCT_NEW table
Dim sql = "SELECT c.FirstName, c.LastName, a.AcctName, a.AcctNum, a.NewAcct, a.Balance " & _
"FROM CustInfo c INNER JOIN ACCT_NEW a ON a.AcctNum = c.NumCuenta " & _
"WHERE NumCuenta = #SocioNum "
Using conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo
With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
.CuentaName = rdr.GetString(2),
.AcctNum = rdr.GetValue(3),
.AcctFull = rdr.GetValue(4),
.Balance = rdr.GetValue(5)
})
End While
End Using

retrieving whole database into dataset

I have access db with 3 different tables,I want to load the whole database into dataset so I will be able to work with the data without load the db serval times.
all the examples of working with dataset are showing how to get part of the database using ".fill"
for example :
OleDbCommand CommandObject = new OleDbCommand ("Select * from employee");
OleDbAdapter myDataAdapter = new OleDbAdapter (null, con);
myDataAdapter.SelectCommand = CommandObject;
myDataAdapter.Fill (myDataSet, "EmployeeData");
this example load only from employee but how can I etrieve the all tables in once into dataset?
in xml for instance there is command to load all the document to dataset with:" dataset.ReadXml"
How can I achive it in access db?
Thanks for any help
Baaroz
Protected Function getDataSetAndFill(ByRef connection As OleDb.OleDbConnection,
Optional ByVal isExportSchema As Boolean = True) As DataSet
Dim myDataSet As New DataSet
Dim myCommand As New OleDb.OleDbCommand
Dim myAdapter As New OleDb.OleDbDataAdapter
myCommand.Connection = connection
'Get Database Tables
Dim tables As DataTable = connection.GetOleDbSchemaTable( _
System.Data.OleDb.OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})
'iterate through all tables
Dim table As DataRow
For Each table In tables.Rows
'get current table's name
Dim tableName As String = table("TABLE_NAME")
Dim strSQL = "SELECT * FROM " & "[" & tableName & "]"
Dim adapter1 As New OleDb.OleDbDataAdapter(New OleDb.OleDbCommand(strSQL, connection))
adapter1.FillSchema(myDataSet, SchemaType.Source, tableName)
'Fill the table in the dataset
myCommand.CommandText = strSQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myDataSet, tableName)
Next
''''''''''''''''''''''''''''''''''''''
'''' Add relationships to dataset ''''
''''''''''''''''''''''''''''''''''''''
'First, get relationships names from database (as well as parent table and child table names)
Dim namesQuery As String = "SELECT DISTINCT szRelationship, szReferencedObject, szObject " & _
"FROM MSysRelationships"
Dim namesCommand As New System.Data.OleDb.OleDbCommand(namesQuery, connection)
Dim namesAdapter As New System.Data.OleDb.OleDbDataAdapter(namesCommand)
Dim namesDataTable As New DataTable
namesAdapter.Fill(namesDataTable)
'Now, get MSysRelationship from database
Dim relationsQuery As String = "SELECT * FROM MSysRelationships"
Dim command As New System.Data.OleDb.OleDbCommand(relationsQuery, connection)
Dim adapter As New System.Data.OleDb.OleDbDataAdapter(command)
Dim relationsDataTable As New DataTable
adapter.Fill(relationsDataTable)
Dim relationsView As DataView = relationsDataTable.DefaultView
Dim relationName As String
Dim parentTableName As String
Dim childTablename As String
Dim row As DataRow
For Each relation As DataRow In namesDataTable.Rows
relationName = relation("szRelationship")
parentTableName = relation("szReferencedObject")
childTablename = relation("szObject")
'Keep only the record of the current relationship
relationsView.RowFilter = "szRelationship = '" & relationName & "'"
'Declare two arrays for parent and child columns arguments
Dim parentColumns(relationsView.Count - 1) As DataColumn
Dim childColumns(relationsView.Count - 1) As DataColumn
For i As Integer = 0 To relationsView.Count - 1
parentColumns(i) = myDataSet.Tables(parentTableName). _
Columns(relationsView.Item(i)("szReferencedColumn"))
childColumns(i) = myDataSet.Tables(childTablename). _
Columns(relationsView.Item(i)("szColumn"))
Next
Dim newRelation As New DataRelation(relationName, parentColumns, childColumns, False)
myDataSet.Relations.Add(newRelation)
Next
If isExportSchema Then
Dim schemaName = GetXmlSchemaFileName()
If File.Exists(schemaName) Then File.SetAttributes(schemaName, FileAttributes.Normal)
myDataSet.WriteXmlSchema(schemaName)
End If
Return myDataSet
End Function
You should just call the OleDbDataAdapter.Fill method with different SelectCommands and pass the same DataSet but different table names inside. In this case, your dataSet will contain different filled tables.

Resources