How to sort DataGridView Column by date in VB visual studio 2012? - vb.net

In my DGV, I have date list in the column (1):
11-Sep-2014
11-May-2011
11-Jan-2014
11-Mar-2014
12-Sep-2010
how to get descending result like this:
11-Sep-2014
11-Mar-2014
11-Jan-2014
11-May-2011
12-Sep-2010
The Column(1) is not DateTime type but SortText type, I must set string like that. Could it sorted?
I have tried using code:
DGV.Columns(1).SortMode = DGV.Sort(DGV.Columns(1), System.ComponentModel.ListSortDirection.Descending)
but it's useless, it don't sort by date :(
this is my DGV:
Okeh, this is my DGV code in brief:
Imports System.Data.OleDb
Public Class LapTransaksiSimpanan
Public Sub Koneksi()
str = "provider=microsoft.jet.oledb.4.0;data source=dbkoperasi.mdb"
Conn = New OleDbConnection(str)
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
End Sub
Sub TampilGrid()
da = New OleDbDataAdapter("select * from LapTransaksiSimpanan", Conn)
ds = New DataSet
da.Fill(ds, "LapTransaksiSimpanan")
DGV.DataSource = ds.Tables("LapTransaksiSimpanan")
'on the below I wanna to sort the column, my code below is useless :(
DGV.Sort(DGV.Columns(1), System.ComponentModel.ListSortDirection.Descending)
DGV.Columns("ID_Simpanan").Width = 120
DGV.Columns("NAK").Width = 37
DGV.Columns("Tanggal").Width = 75
DGV.Columns("Jumlah").Width = 110
End Sub
Private Sub Setoran_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Koneksi()
Call TampilGrid()
End Sub
End Class

There's a difference between storing and displaying data.
You need to change you database table schema. The Tanggal column should be of type date or datetime. When you've fixed this, it's trivial to display dates using a custom format:
Me.DGV.Columns("Tanggal").DefaultCellStyle.Format = "dd-MMM-yyyy"
If you for some reason cannot change the schema, then you need to create a custom comparer by implementing IComparer. There's an example at the bottom of this MSDN page.

Dim tnd As Date
For Me.i = 0 To X1.RowCount - 2
tnd = X1.Item(1, i).Value
X1.Item(6, i).Value = tnd.ToOADate.ToString
Next
X1 is DataGridView
Column 1 would have your date ex 5/4/1987
Column 6 would be calculated as MS date number in integer and must be converted to string.
Make sure X1 grid is Sort enabled
Now simply click on Column 6 header to sort.
Hope that works.

Related

MAX & MIN Value on GridView Column VB.NET

I am developing a small program to get the maximum of a specific column in a gridview (DevExpress), but I could not execute it as I wanted.
Can you support me in seeing where I have the error?
Dim cells() As GridCell = GridView2.GetSelectedCells()
Dim values As New List(Of Decimal)()
For i As Integer = 0 To GridView2.RowCount - 1
Dim value As Decimal = Convert.ToDecimal(GridView2.GetRowCellValue(cells(i).RowHandle, cells(i).Column))
values.Add(value)
Next i
values.Sort()
MsgBox(values.Max().ToString())
Regards.
With the built in DataGridView, the number of rows can be Rows.Count -2 because there is an extra row for the user to enter a new record. I have no idea if DevExpress works that way but it is worth a try.
For i As Integer = 0 To GridView2.RowCount - 2
If your GridView uses a DataTable as a DataSource, then the following code might help. If the DataTable is still available then just start with that. Otherwise extract it from the grid.
DataTable does not implement IEnumerable but there is an extension method to get the interface (.AsEnumerable).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = DirectCast(DataGridView1.DataSource, DataTable)
Dim maxValue = Aggregate r In dt.AsEnumerable
Into MaxID = Max(r("ID")) '"ID" is the name of a column
MessageBox.Show(maxValue.ToString)
End Sub
Same thing for Min just change Max to Min.
Calculate Total Summary for Grid Column
gridView1.Columns("UnitsInStock").Summary.Add(DevExpress.Data.SummaryItemType.Average, "UnitsInStock", "Avg={0:n2}")
gridView1.Columns("UnitsInStock").Summary.Add(DevExpress.Data.SummaryItemType.Sum, "UnitsInStock", "Sum={0}")
Dim item As GridColumnSummaryItem = New GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Max, "UnitsInStock", "Max={0}")
gridView1.Columns("UnitsInStock").Summary.Add(item)
Devexpress Documentation:
https://documentation.devexpress.com/WindowsForms/DevExpress.XtraGrid.Columns.GridColumn.Summary.property
https://documentation.devexpress.com/WindowsForms/9677/Controls-and-Libraries/Data-Grid/Examples/Summaries/How-to-Calculate-Single-Total-Summary-for-Grid-s-Column

i m not able to fix my auto id generator

I am able to successfully generate an id on form load but when I leave that form and try to load it again the id generated is the same as the previous one
Try
Dim num As Integer
conn.ConnectionString = String.Format("server=localhost;user id=root;password=root;database=rishab")
conn.Open()
sqlcommand = New MySqlCommand("select max(ID) from inc", conn)
sqlcommand.ExecuteNonQuery()
If IsDBNull(sqlcommand.ExecuteScalar) Then
num = 1
id5.Text = num
Else
num = sqlcommand.ExecuteScalar + 1
id5.Text = num
End If
sqlcommand.Dispose()
conn.Close()
conn.Dispose()
Catch ex As Exception
End Try
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
autogenerate()
End Sub
If I understand this correctly you need to declare your num Integer as public. It will then hold the latest value and when you re-load the form it will count on from the latest value. Do this before your form class starts or I will personally add this in a module with all my other public strings, booleans and integers.
''In a module add -
Public num As Integer
''Do not add a value here as in Public num as Integer = 0 as it will give the value 0 every time you make a call to it.
''Also remember to handle the value throughout your app, change back to 0 or leave it to the last value etc.

Database Lookup From ComboBox selection

I have a question about database values and how to determine the id of a value that has been changed by the user at some point.
As it is currently set up there is a combobox that is populated from a dataset, and subsequent text boxes whose text should be determined by the value chosen from that combobox.
So let's say for example you select 'Company A' from the combobox, I would like all the corresponding information from that company's row in the dataset to fill the textboxes (Name = Company A, Address = 123 ABC St., etc.,)
I am able to populate the combobox just fine. It is only however when I change the index of the combobox that this specific error occurs:
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Data type mismatch in criteria expression.
Here is the corresponding code:
Imports System.Data.OleDb
Public Class CustomerContact
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|datadirectory|\CentralDatabase.accdb;")
Dim da As New OleDbDataAdapter()
Dim dt As New DataTable()
Private Sub CustomerContact_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cn.Open()
da.SelectCommand = New OleDbCommand("select * from Customers", cn)
da.Fill(dt)
Dim r As DataRow
For Each r In dt.Rows
cboVendorName.Items.Add(r("Name").ToString)
cboVendorName.ValueMember = "ID"
Next
cn.Close()
End Sub
Private Sub cboVendorName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboVendorName.SelectedIndexChanged
cn.Open()
da.SelectCommand = New OleDbCommand("select * from Customers WHERE id='" & cboVendorName.SelectedValue & "'", cn)
da.Fill(dt)
Dim r As DataRow
For Each r In dt.Rows
txtNewName.Text = "Name"
txtAddress.Text = "Address"
Next
cn.Close()
End Sub
The error is caught at Line 24 of this code, at the second da.Fill(dt) . Now obviously from the exception I know that I am sending in a wrong datatype into the OleDbCommand, unfortunately I am a novice when it comes to SQL commands such as this. Also please keep in mind that I can't even test the second For loop, the one that is supposed to fill the Customer information into textboxes (for convenience I only copied the first two textboxes, of which there are nine in total). I am think I could use an If statement to determine if the row has been read, and from there populate the textboxes, but I will jump that hurdle when I can reach it.
Any guidance or suggestions would be much appreciated. Again I am a novice at managing a database and the code in question pertains to the project my current internship is having me write for them.
Since you already have all the data from that table in a DataTable, you dont need to run a query at all. Setup in form load (if you must):
' form level object:
Private ignore As Boolean
Private dtCust As New DataTable
...
Dim SQL As String = "SELECT Id, Name, Address, City FROM Customer"
Using dbcon = GetACEConnection()
Using cmd As New OleDbCommand(SQL, dbcon)
dbcon.Open()
dtCust.Load(cmd.ExecuteReader)
End Using
End Using
' pk required for Rows.Find
ignore = True
dtCust.PrimaryKey = New DataColumn() {dtCust.Columns(0)}
cboCust.DataSource = dtCust
cboCust.DisplayMember = "Name"
cboCust.ValueMember = "Id"
ignore = False
The ignore flag will allow you to ignore the first change that fires as a result of the DataSource being set. This will fire before the Display and Value members are set.
Preliminary issues/changes:
Connections are meant to be created, used and disposed of. This is slightly less true of Access, but still a good practice. Rather than connection strings everywhere, the GetACEConnection method creates them for me. The code is in this answer.
In the interest of economy, rather than a DataAdapter just to fill the table, I used a reader
The Using statements create and dispose of the Command object as well. Generally, if an object has a Dispose method, put it in a Using block.
I spelled out the columns for the SQL. If you don't need all the columns, dont ask for them all. Specifying them also allows me to control the order (display order in a DGV, reference columns by index - dr(1) = ... - among other things).
The important thing is that rather than adding items to the cbo, I used that DataTable as the DataSource for the combo. ValueMember doesn't do anything without a DataSource - which is the core problem you had. There was no DataSource, so SelectedValue was always Nothing in the event.
Then in SelectedValueChanged event:
Private Sub cboCust_SelectedValueChanged(sender As Object,
e As EventArgs) Handles cboCust.SelectedValueChanged
' ignore changes during form load:
If ignore Then Exit Sub
Dim custId = Convert.ToInt32(cboCust.SelectedValue)
Dim dr = dtCust.Rows.Find(custId)
Console.WriteLine(dr("Id"))
Console.WriteLine(dr("Name"))
Console.WriteLine(dr("Address"))
End Sub
Using the selected value, I find the related row in the DataTable. Find returns that DataRow (or Nothing) so I can access all the other information. Result:
4
Gautier
sdfsdfsdf
Another alternative would be:
Dim rows = dtCust.Select(String.Format("Id={0}", custId))
This would return an array of DataRow matching the criteria. The String.Format is useful when the target column is text. This method would not require the PK definition above:
Dim rows = dtCust.Select(String.Format("Name='{0}'", searchText))
For more information see:
Using Statement
Connection Pooling
GetConnection() method aka GetACEConnection

Display DataGridView values in text boxes based on matching values - vb.net

I have an SQL query that returns 2 columns of values:
country | number
NA | 1
IN | 2
CN | 3
DE | 4
And so on.
I am trying to do one of the following:
Assign these values to variables I can copy to an excel workbook
Or just use the DGV as a medium to copy values to text boxes.
For example, I have a form with country labels and textboxes next to them. I would want to click a button and have the data copied to the matching text box.
DGV number value where DGV row value = CN would be 3 and that value would be copied to the CN value text box.
If you are only using the DGV as a medium, but not actually displaying it, use a dictionary instead. Output the SQLDataReader using the SQLcommand(cmd) with the country code being the key and the number being the value. Then its as simple as:
Dim dc As Dictionary(Of String, String) = New Dictionary(Of String, String)
Dim cmd As SqlCommand = "your query string"
cmd.Connection.ConnectionString = "your con string"
Using sqlrdr As SqlDataReader = cmd.ExecuteReader()
While (sqlrdr.Read())
dc.Add(sqlrdr(0), sqlrdr(1))
End While
End Using
Then just output to the textbox:
txtNA.Text = dc.Item("NA")
If the countries are fixed as your question refers, then you could use something like this:
First, use the names of the countries to name the TextBoxes (txtNA, txtIN, txtCN,...)
Then you can put this code:
Try
For i = 0 To DataGridView1.RowCount - 1
Me.Controls("txt" & DataGridView1.Rows(i).Cells(0).Value.ToString).Text = _
DataGridView1.Rows(i).Cells(1).Value.ToString()
Next
Catch
End Try
The following will not work 'as is' if using classes via dragging tables from the data source window in the ide. We would need to cast objects not to a DataTable but to the class definition in a TableAdapter, DataSet and BindingSource.
Here is a method which reads from SQL-Server database table, places data into a DataTable, data table become the data source for a BindingSource which becomes the data source for the DataGridView. Using a BindingSource we now use the BindingSource to access row data rather than the DataGridView and it's always best to go to the data source rather than the user interface.
BindingSource.Current is a DataRowView, drill down to Row property then field language extension method to get strongly typed data for the current row if there is a current row as you will note I am using two forms of assertions, first, do we have a data source and is the data source populated then we see if there is indeed a current row.
From here we can set variable, properties or control text to the field values of the current row.
Note in form load I seek a specific country (totally optional) and then if found go to that row.
Least but not last, I like using xml literals when doing SQL in code so there is no string concatenation and we can format the statement nicely.
Public Class Form1
''' <summary>
''' Permits obtaining row data in DataGridView
''' </summary>
''' <remarks></remarks>
Dim bsCountries As New BindingSource
Public Property Country As String
Public Property CountryNumber As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
Using cn As New SqlClient.SqlConnection With
{
.ConnectionString = My.Settings.KarenDevConnectionString
}
Using cmd As New SqlClient.SqlCommand With {.Connection = cn}
' xml literal to make command text
cmd.CommandText =
<SQL>
SELECT [ID],[Country],[Number]
FROM [Countries]
</SQL>.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
dt.Columns("ID").ColumnMapping = MappingType.Hidden
bsCountries.DataSource = dt
DataGridView1.DataSource = bsCountries
' let's try and move to a country
Dim index As Integer = bsCountries.Find("Country", "CN")
If index > -1 Then
bsCountries.Position = index
End If
End Using
End Using
End Sub
''' <summary>
''' Put field values into TextBoxes
''' </summary>
''' <remarks></remarks>
Private Sub DoWork()
If bsCountries.DataSource IsNot Nothing Then
If bsCountries.Current IsNot Nothing Then
Dim row As DataRow = CType(bsCountries.Current, DataRowView).Row
TextBox1.Text = row.Field(Of String)("Country")
TextBox2.Text = row.Field(Of Integer)("Number").ToString
' we can also do this
Me.Country = row.Field(Of String)("Country")
Me.CountryNumber = row.Field(Of Integer)("Number")
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DoWork()
End Sub
End Class

<VB> Highlighting Selected dates from database in Calendar control

I am currently using VB. I want to do a Calendar Control which have dates highlighted/selected. All these dates are retrieved from a database.
First thing I need to know is how to put all the dates into an array
Second thing I need to know is how to highlight all the dates in the array.
I have done some research on the internet and they said something about selectedDates and selectedDates collection and dayrender. But frankly speaking, I can't really find any VB codes regarding this. Dates format will be in dd/MM/yyyy
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String = ConfigurationManager.ConnectionStrings("CleanOneConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select schedule From OrderDetails Where schedule is not null"
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
If (reader.Read()) Then
If (reader.HasRows) Then
While reader.Read()
myCalendar.SelectedDates.Add(CType(reader.GetDateTime(0), Date))
End While
End If
End If
reader.Close()
connection.Close()
myCalendar.SelectedDayStyle.BackColor = System.Drawing.Color.Red
End Sub
End Class
My Calendar
<asp:Calendar ID="myCalendar" runat="server" ShowGridLines="True">
</asp:Calendar>
Updated with what I have done, but still does not show
Thanks for the help
Assume you have a DataTable named myDates, and a Calendar control named myCalendar:
For i As Int = 0 To myDates.Rows.Count - 1
myCalendar.SelectedDates.Add(CType(myDates.Row(i)(0), Date)
Next
You can declare the highlighting in your markup:
<asp:Calendar ID="myCalendar" runat="server">
<SelectedDayStyle BackColor="red" />
</asp:Calendar>
Or programatically:
myCalendar.SelectedDayStyle.BackColor = System.Drawing.Color.Red
UPDATE For SqlDataReader (VB.NET this time)
If reader.HasRows Then
While reader.Read()
myCalendar.SelectedDates.Add(CType(reader(0), Date)
End While
End If
UPDATE based on OP's code
Are you getting any errors when the code runs? SqlDataReader.GetDateTime will throw an InvalidCastException if the column being read isn't a DateTime column.
I'm wondering if it's a format issue? Can you verify the data type of the column in the database, as well as the format the date is being stored in?
I've modified your code a bit with a couple of suggestons.
Imports System.Data.SqlClient
Partial Class _Default Inherits System.Web.UI.Page
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String = ConfigurationManager.ConnectionStrings("CleanOneConnectionString").ConnectionString
' Using blocks will automatically dispose of the object, and are
' pretty standard for database connections
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select schedule From OrderDetails Where schedule is not null"
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
' This is not needed - in fact, this line will "throw away"
' the first row in the row collection
'If (reader.Read()) Then
If (reader.HasRows) Then
While reader.Read()
myCalendar.SelectedDates.Add(CType(reader.GetDateTime(0), Date)) End While
End If
reader.Close()
' Not needed because of the Using block
'connection.Close()
End Using
myCalendar.SelectedDayStyle.BackColor = System.Drawing.Color.Red
End Sub
End Class
For the second part of your question, you can see on this post how to highlight specified days, albeit using C# syntax.
I'm going to assume a L2S format is being used to fetch the dates for now (comment with actual implementation if you need better detail).
I would recommend the dates you want to select be held in a variable on the form (instead of scoped to the function) to prevent database queries running everytime a day is rendered. With that in mind, here is some sample code (free-hand so please excuse and comment on basic/troubling syntax issues):
Private DatesToHighlight As IEnumerable(Of Date)
' implementation details provided so commented this bit out, see EDIT below
'Protected Sub PopulateDatesToHighlight()
' DatesToHighlight = db.SomeTable.Select(Function(n) n.MyDateField)
'End Sub
Protected Sub DayRenderer(ByVal object As Sender, ByVal e As DayRenderEventArgs)
If DatesToHighlight.Contains(e.Day.Date) Then
e.Cell.BackColor = System.Drawing.Color.Red
End If
End Sub
As specified in the question I linked, you'll need to change the markup for the calendar control to provide the ondayrender parameter like so ondayrender="DayRenderer"
Regarding changing your dates to an array, it depends what format they are in at the start. If in anything that inherits from IEnumerable then you can use ToArray(). If they are just variables you can initialise the array with the dates
Dim myDates() As Date = {dateVar1, dateVar2}
Hope that helps?
EDIT: (In response to OP's addition of code)
To get from your data reader to an array (though I'm not convinced you need an array) I would do the following:
' using the variable I declared earlier
DatesToHighlight = New IEnumerable(Of Date)
If reader.HasRows Then
Dim parsedDate As Date
While reader.Read()
If Date.TryParse(reader(0), parsedDate) Then
DatesToHighlight.Add(parsedDate)
End If
End While
End If
Dim myArrayOfDates() As Date = DatesToHighlight.ToArray()