Remove duplicated rows on gridview - html

Hi There I have the following grid view developed with vb.net and html
This is the code to fill the gridview
Private Sub BindGrid()
Dim modelo As String = txtModelo.Text
Dim linha As String = txtLinha.Text
Dim data As String = txtData.Text
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM tempo where timermodelo = #timermodelo and timerlinha = #timerlinha and timerdata = #timerdata")
Using sda As New MySqlDataAdapter()
cmd.Parameters.AddWithValue("#timermodelo", modelo)
cmd.Parameters.AddWithValue("#timerlinha", linha)
cmd.Parameters.AddWithValue("#timerdata", data)
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End Sub
My question is, is it possible to remove the duplicated rows on the column Operador, Posto, Linha and Modelo?
And also how can I form the date to show 'dd-mm-yyyy'?
Actually, I want to merge these values, if they are the same, show just one time
Sorry if it is difficult to understand, if more information is needed let me know
Thanks in advance

Remove duplicates : Why don't you use SqlStatement that return rows without duplication, depending on your Database type 'you did not mention', if this is achievable in your SqlStatement then this problem is solved.
Format Date in GridView1 cell : Use GridView1_CellFormatting event [ Where your Date ColumnIndex = 4] as follows
Private Sub GridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
If Not IsNothing(e.Value) Then
If e.ColumnIndex().ToString = 4 And IsDate(e.Value) Then
e.Value = Format(e.Value, "dd-mm-yyyy")
End If
End If
End Sub
I want to merge these values, if they are the same
What values are we talking about here ?

Related

How to display data from mysql base from Dropdownlist selection

i want to display mysql data base from the dropdownlist. i populate data from dropdownlist using this code and it works perfectly. in this code it will show the productnames in the dropdownlist
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT tbl_productid,tbl_productname FROM tbl_products")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
cmbProducts.DataSource = cmd.ExecuteReader()
cmbProducts.DataTextField = "tbl_productname"
cmbProducts.DataValueField = "tbl_productid"
cmbProducts.DataBind()
con.Close()
End Using
End Using
cmbProducts.Items.Insert(0, New ListItem("Select Product"))
End If
Now base from the selected product name i want to display its productID to textbox. but this code gives me no output? i dont know what is wrong with my code anyone who can help me
This is code
Protected Sub cmbProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cmbProducts.SelectedIndexChanged
'MsgBox("Hellow World!", MsgBoxStyle.Critical)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim con As New MySqlConnection(constr)
con.Open()
Dim cmd As New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '" + cmbProducts.Text + "'", con)
Dim sda As New MySqlDataAdapter(cmd)
'Dim dr As New MySqlDataReader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read Then
txtProductID.Text = dr.GetValue(0)
End If
con.Close()
con.Dispose()
End Sub
Ok, a few things.
The drop list has two columns. data value (id), and data text.
What you have looks good.
However, when you get/grab/use the drop list, then you have this:
DropDownList1.Text - this will return the data value (1st column)
DropDownList1.SelectedValue - this will ALSO return data value (1st column)
DropDownList1.SelectedItem.Text - this gets the 2nd display text value (2nd column)
So, because a LOT of drop lists can be only one column, then the .text and .SelectedValue can both be used. (in other words, you can use .text, but it gets the first value, and since a lot of drop lists might only have one column, then .text always gets that first value). But I would consider the habit of SelectedValue for the column that drives the drop list.
In your case, you really do want the 2nd column, and thus you want to use:
DropDownList1.SelectedItem.Text
So,
New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '"
+ cmbProducts.SelectedItem.Text + "'", con)
I used my own data to demonstrate. Also I used given control names in my test program. This is not what your want to do in your application. Your control names are good.
I broke the code into the data access part and the user interface code. There is very little code in the actual event procedure.
You have set the .DataValueField to the id so you can retrieve that value in the SelectedIndexChanged event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillDropDownList()
End If
End Sub
Private Sub FillDropDownList()
Dim dt = GetListBoxData()
DropDownList1.DataTextField = "Name"
DropDownList1.DataValueField = "ID"
DropDownList1.DataSource = dt
DropDownList1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim dt = New DataTable
Dim Query = "Select Top 10 ID, Name
FROM Coffees;"
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(Query, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
TextBox1.Text = DropDownList1.SelectedValue
End Sub
There is no need to make a second round trip to the database. You already have the data you require.

vb.net setting data source to combobox

i want to set a data source to my combobox when i run there s no error but it keeps showing zeros in the combobox
Dim cnx As New MySqlConnection("datasource=localhost;database=bdgeststock;userid=root;password=")
Dim cmd As MySqlCommand = cnx.CreateCommand
Dim da As MySqlDataAdapter
Dim ds As New DataSet
If ConnectionState.Open Then
cnx.Close()
End If
cnx.Open()
cmd.CommandText = "SELECT idf,(prenom + ' ' + nom) AS NAME FROM fournisseur "
da = New MySqlDataAdapter(cmd)
cnx.Close()
da.Fill(ds)
da.Dispose()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "idf"
ComboBox1.DisplayMember = "NAME"
For ComboBox data source you probably don't need heavy Data Set or DataTable - collection of plain object will do the job.
Another approach would be to move representation logic to the vb.net code and leave sql server to do persistence logic only.
Public Class Fournisseur
Public ReadOnly Property Id As Integer
Public ReadOnly Property Name As String
Public Sub New(id As Integer, prenom As String, nom As String)
Id = id
Name = $"{pronom} {nom}".Trim()
End Sub
End Class
You can create dedicated function to load data
Private Function LoadItems() As List(Of Fournisseur)
Dim query = "SELECT idf, prenom, nom FROM fournisseur"
Using connection As New MySqlConnection(connectionString)
Using command As New MySqlCommand(query, connection)
connection.Open()
Dim items = new List(Of Fournisseur)()
Using reader AS MySqlDataReader = command.ExecuteReader()
While reader.Read()
Dim item As New Fournisseur(
reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2)
)
items.Add(item)
End While
End Using
Return items
End Using
End Using
End Function
Then usage will look pretty simple
ComboBox1.ValueMember = "Id"
ComboBox1.DisplayMember = "Name"
ComboBox1.DataSource = LoadItems()
I think the problem is in your sql, and mysql is performing some sort of numeric addition on prenom plus nom and producing 0
Try
CONCAT(prenom, ' ', nom) as name
In your sql instead. I prefer using concat in most RDBMS for concatenating strings because is is more consistent with its behaviour on NULLs - in sqlserver, using the concat operator of plus on something like 'a' + null results in NULL but in oracle 'a' || null is a - in both the CONCAT behaviour is consistent
Here's a full code with all my recommendations:
Dim cnstr = "datasource=localhost;database=bdgeststock;userid=root;password="
Dim cmd = "SELECT idf, CONCAT(prenom, ' ', nom) AS nom FROM fournisseur "
Using da As New MySqlDataAdapter(cmd, cnstr)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.ValueMember = "idf"
ComboBox1.DisplayMember = "nom"
End Using
Tips:
you don't need to mess around with the connection: dataadapter will create/open/close it for you
use a datatable not a dataset
use Using
use the constructor of MySqlDataAdapter that takes a connectionstring and a command text- shorter and nearer in this case. I only use the constructor that takes a DbConnection if I'm manually enrolling multiple commands in a transaction etc

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

Accessing values from a loop in VB.Net from another function using button click event handler

I am trying to create a new POS system using VB.Net but am a beginner with it. I have a problem. Basically I use an online SQL database using which different categories of items for the POS can be added by the admin. Since all the items have been stored in an SQL table I have managed to retrieve that information based on categories and display them in the form of buttons on my POS system.
Now the problem is that the loop holds all the information related to the different buttons created and when I try to access the value of the current category being clicked on from another button it doesn't seem to give me the current value but instead gives me the last value which was updated in the loop. I'm leaving an example of the code below:
Imports MySql.Data.MySqlClient
Public Class Form13
Dim arr(100) As String
Public verifier(1) As Integer
Dim counter As Integer
Public value As String
Public Sub Form13_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim point As Integer
Dim point1 As Integer
point = 20
point1 = 100
counter = 0
Label2.Text = Form12.selected_value
Dim connection As New MySqlConnection
connection.ConnectionString = ("host=localhost;user=root;password=;database=pos;")
connection.Open()
Dim command As New MySqlCommand("select * from categories", connection)
Dim reader As MySqlDataReader
reader = command.ExecuteReader
While reader.Read()
Dim button As New Button
value = reader.GetString("category_name")
button.Name = value
button.Text = value
button.Height = 50
button.Width = 190
button.Font = New Font("arial", 11)
button.Location = New Point(point, point1)
Me.Controls.Add(button)
point1 = point1 + 50
counter = counter + 1
verifier(0) = counter
arr(counter) = value
AddHandler button.Click, AddressOf button_Click
button_Click()
End While
End Sub
Private Sub button_Click()
MsgBox(arr(counter))
End Sub
End Class
Shown above is the code where the category name is gathered from the MySQL table and later a single button is being reused until all the buttons have been created for all existing category names in the MySQL table. Now the outcome I would like is to have the name of the category when the relevant button is being clicked in the form of a MsgBox in the button handler. Any help would be very much appreciated.
The SQL table is being hosted using XAMPP and a screenshot of the category table used in the code above is shown below:
enter image description here
The problem is, that you have a the String value which is a referenced object.
Your loop adds the same reference to the string with every iteration of your loop.
The reference tells your programm where to look for the value in you RAM. The value for the same object gets updated every iteration so every entry has the same data.
You can fix this by declaring the Public value as String within the loop. That way every time you create a new reference.
Remove this line:
Public value As String
Change this line:
value = reader.GetString("category_name")
to:
Dim value as String = reader.GetString("category_name")
I used SQL Server because that is where I had a sample database. Just use the sender's Name or Text to find what category button was clicked.
Imports System.Data.SqlClient
Public Class Form3
Public Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value As String
Dim point As Integer
Dim point1 As Integer
point = 20
point1 = 100
Label2.Text = Form12.selected_value
Using connection As New SqlConnection
connection.ConnectionString = My.Settings.BuildersConnectio
Dim command As New SqlCommand("select * from Builders", connection)
Dim reader As SqlDataReader
connection.Open()
reader = command.ExecuteReader
While reader.Read()
Dim button As New Button
value = reader.GetString(1)
button.Name = value
button.Text = value
button.Height = 50
button.Width = 190
button.Font = New Font("arial", 11)
button.Location = New Point(point, point1)
Me.Controls.Add(button)
point1 = point1 + 50
AddHandler button.Click, AddressOf button_Click
End While
End Using
End Sub
Private Sub button_Click(sender As Object, e As EventArgs)
Dim btn As Button = CType(sender, Button)
Dim ProductCategory = btn.Name
MessageBox.Show(ProductCategory)
End Sub
End Class

How do I loop Through Each Records in SQL server with Time Gap

I am making a CMS portal for my company which will fetch records from SQL server using ASP.NET:
My problem is that when I fetch values it only shows the last one. But my need is that it should display one by one values with say 5-10 seconds gap in between here is my code:
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim connectionString As String = "Data Source=soemserv;Initial Catalog=data;User Id=master; Password=hushotn;"
Dim conn As New SqlConnection(connectionString)
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
conn.Open()
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
End While
End Sub
End Class
How do I loop though each record I tried Do and Loop but its not working...
Thanks in advance!
EDIT
One Step Ahead with no LUCK!!!!
I have written this code but still getting the last row only
For I As Integer = 0 To 15
lblTemp.Text = I.ToString
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status where SrNo='" + lblTemp.Text + "';", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
Thread.Sleep(2000)
End While
Next
Note I have dynamically given rows i.e 0 to 15
Please guide me!!
Only the last values are printed because : you are fetching a group of rows(data) through the readr and in first iteration of the while loop the first rows(data) are copied to the controls then for the second iteration the contents in the controls are over written with the second row. This will happens in each iteration hence only the last data are displayed.
- This can be avoided by using
Group of controls which are dynamically created(but not practical and good)
using DataGridView(grid) to display the items How to do this
**The method you ware suggested (using Timer) is also possible but it is not a good programming practice only the last values ware displayed all the others flashed for a duration of 5-10 seconds **