Database query result to display in Label VB.net - asp.net

I have a label in which I want to display my database query result. But the label displaying only first row not all the records. Can anyone here could help me with this? Tried searching but I found other answers confusing. Please help me.
Here is what I have so far.
FrontEnd
<asp:Label ID="Resulttext" runat="server" Text=""></asp:Label>
Backend
Protected Sub getUser()
Dim dt As New DataTable()
Dim conn As SqlConnection = New SqlConnection("myconnectionhere")
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("mysqlhere", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
Resulttext.Text = dt.Rows(0)("Fullname").ToString
End If
conn.Close()
End Sub
What I'm doing wrong? Thank you.

Already solve the problem and here is the answer.
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
Resulttext.Text = dt.Rows(i)("Fullname").ToString & " " & Resulttext.Text
Next
End If

Resulttext.Text = dt.Rows(0)("Fullname").ToString
You are writing above code for display record in the Lable.
Meaning of above code is dt.Rows(RowIndex)(ColumnIndex/"Column valuse")
You passed 0 in the RowIndex Means it gives you First row and passed "FullName" in column value , So it gives fullname value of First row.
That's why it displays only one record.
For display all the value of FullName you have to change your query as below.
select distinct t1.id,
STUFF(
(SELECT ', ' + FullName
FROM yourtable t2
where t1.id = t2.id
FOR XML PATH (''))
, 1, 1, '') AS fullname
from yourtable t1;
Thus it gives fullName as comma separated and then you can write code
Resulttext.Text = dt.Rows(0)("Fullname").ToString
And it gives CSV for fullname and displays in the label

Related

How to find specific string and dynamic string

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

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

Refresh ComboBox in Windows form with datasource retains value even when datasource is empty

I have 2 comboboxes, cmbstud and cmbhostel. They are filled from the database by binding the datasource to the datatable. As I update, the cmbstud updates accordingly. When I update the last record the datatable empties, but cmbstud still retains the value. Cmbhostel data is bound to change index of cmbstud.
In the form load event I have this code:
Dim cmd As New SqlCommand("SELECT stud_id,name FROM student_details WHERE stud_id NOT IN (SELECT stud_id FROM student_details WHERE hostel_id!=0)", sqlcont.Conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim dat As New DataTable
Dim j As Integer
For j = 0 To dat.Rows.Count - 1
dr.Read()
Next
dat.Load(dr)
cmbstud.DisplayMember = "name"
cmbstud.ValueMember = "stud_id"
cmbstud.DataSource = New BindingSource(dat, Nothing)
dr.Close()
sqlcont.Conn.Close()
In my btnhostel for updating I have the following queries implemented and the following code to reload the form to refresh my datasources:
"UPDATE hostel SET in_use=in_use+1 WHERE hostel_id=#hostid"
"UPDATE student_details SET hostel_id=#hostid where stud_id=#stud_id"
frmallocateHostel_Load(Nothing, Nothing)
Cmbstud index change evnt code:
Dim sqcm5 As New SqlCommand("Select hostel.hostel_id,hostel.hostel_name From hostel Inner Join student_details On student_details.gender = hostel.hostel_gender where student_details.stud_id =" & cmbstud.SelectedValue.ToString & " ", sqlcont.Conn)
Dim datreadr5 As SqlDataReader = sqcm5.ExecuteReader
Dim dt5 As New DataTable
Dim n As Integer
For n = 0 To dt5.Rows.Count - 1
datreadr5.Read()
Next
dt5.Load(datreadr5)
cmbhostel.ValueMember = "hostel_id"
'asign value & display member b4 datasource to avoid errors
cmbhostel.DisplayMember = "hostel_name"
cmbhostel.DataSource = dt5
There are some similar questions: ComboBox has its old value after Clear(); however, they don't address my issue.
changing this did the trick:
Dim b As New BindingSource()
b.DataSource = dat
cmbstud.DataSource = b
b.ResetBindings(False)

how to count the record in the database?

i have this database table called people
People
peopleID peopleName relationship customerID
1 A aunty 1
2 B aunty 1
3 C second uncle 1
4 D aunty 2
how am i going to count the number of people where the customerID = 1 and if the relationship is the same, it is counted as 1
so from the database table above, i should get the result of 3 and put the result of 3 in Label1 in gridview?
i can get the count value for the only where the customerID =1 but i can't figure out how am i going to count if the relationship part
Protected Sub GridView2_RowDataBound(sender As Object, e As
System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Do your processing here...
Dim txt As TextBox = DirectCast(e.Row.FindControl("Label1"), TextBox)
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
'Dim sql As String
Dim connectionString = ConfigurationManager.ConnectionStrings("ProjData").ConnectionString
Dim myConn As New SqlConnection(connectionString)
Dim cmd = "Select * From People Where customerID='" & Session("customerID") & "' "
' Dim myCmd As New SqlCommand(cmd, myConn)
Try
myConn.Open()
Dim myCmd As New SqlCommand(cmd, myConn)
adapter.SelectCommand = myCmd
adapter.Fill(ds, "People")
adapter.Dispose()
myCmd.Dispose()
txt.Text = ds.Tables(0).Rows.Count
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End If
End Sub
You should wrap your SqlConnection in a using statement (not sure how you do that in VB). In your example you don't close the connection, the using statement does this for you automatically (the alternative is to close the connection in a finally block)
When i correctly understand your question, the following SQL Statement should give you the count as you need it.
Select count(peopleID)
From People
Where customerID = 1
Group by relationship, customerID
If this answer didn't solve your problem please add further information to your question.
In your code, you fetch all the rows and then count them. You can also execute a query that will count the number of rows on the server. This will perform much better!
string sql = "SELECT COUNT(*) FROM People Where customerID='" & Session("customerID") & "' "
...
int rowCount = myCmd.ExecuteScalar();
If you want to count the number of rows with the same relationship, you have to use a group by.
You have to change your sql to:
string sql = 'SELECT COUNT(peopleId) FROM People Where customerID='" & Session("customerID") & "' "GROUP BY relationship, customerId"

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