How to change the datetime value to year only, that retrieve from database table and show on combobox.display member? - oledb

i got a list of datetime value from ()table look like these: 31/12/14 4:45:30 PM
31/12/14 4:45:30 PM
31/12/14 4:45:30 PM
31/12/14 4:45:30 PM
31/12/14 4:45:30 PM
AND i want them to only show like e.g.:, in the combobox.display member
2014
2015
2016
2017
i know i wrote like below might have datatypes error, but anyone can correct me or guide me on this??
Public Sub combothing()
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim selectme As String = "SELECT * FROM yeartbl"
Dim cmd As New OleDbCommand(selectme, connection)
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
da.SelectCommand = cmd
da.Fill(ds)
da.Fill(ds, "yeartbl")
dt = ds.Tables("yeartbl")
connection.Close()
Me.ComboBox1.DataSource = ds.Tables(0)
Me.ComboBox1.ValueMember = "YID"
**Convert.ToDateTime(Me.ComboBox1.DisplayMember = "Years").Date.Year.ToString()**
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

One of the things that you can do (assuming we work against Excel) is, when you already filled DataSet, add one more column
ds.Tables(0).Columns.Add("year", System.Type.GetType("System.Integer"))
For each (r as row in ds.Tables(0).Rows)
r("year") = DirectCast(r("YTD"), DateTime).Year 'assuming it is not null column
Next
Now, set Value Member to
Me.ComboBox1.ValueMember = "Year"
Also, needs more research, you may can do this:
"SELECT *, FunctionTOConvertToDate(YTD) as year FROM yeartbl"

Related

when datetime objects casted to string, language of month name not match with culture info

I set culture info to turkish, but when datetime object casted to string(""+h.DogumTarihi) it looks like; Jan.26.1989
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("tr-TR");
EvlilikRaporuVM mdl = (from r in raporRepo
join h in hastaRepo on r.HastaTc equals h.HastaTc
select new EvlilikRaporuVM
{
ID = Id,
BirthDate = "" + h.DogumTarihi,
...
how to force datetime object to get language info from current culture?
You need to specify the CurrentCulture:
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR");
With this, the following:
Console.WriteLine(DateTime.Now.ToLongDateString());
Outputs:
25 Eylül 2018 Salı

How can I populate a list with a default value for records that don't exist in a database?

I want to take records in a database over the past year, sum the records by month, and then populate a line graph with that information. However, when a month has no records, I can't seem to figure out how to get that into the proper location in the list. For example, if nothing exists for September or October, my line graph just skips those months. I tried checking and adding the months in afterwards, but I can't get them in sequential order. Any help?
Dim PointTotals = db.MemberRewards _
.Where(Function(r) sitewideFilterSelectedMemberIds.Contains(r.memberId) And r.supplier.name <> "AudStandard" And r.transactionDate >= startDate And r.transactionDate <= EndDate) _
.GroupBy(Function(r) New With {r.transactionDate.Value.Month, r.transactionDate.Value.Year}) _
.Select(Function(gr) New With {.month = gr.Key.Month, .year = gr.Key.Year, .totalPoints = gr.Sum(Function(r) r.points)}) _
.OrderBy(Function(gr) gr.year).ThenBy(Function(gr) gr.month)
Dim firstPeriodDate As Date
Dim currentDate As Date = DateAdd(DateInterval.Month, -1, startDate)
If PointTotals.Count > 0 Then
Dim firstPeriod = PointTotals.First
firstPeriodDate = CDate(firstPeriod.month & "/1/" & firstPeriod.year)
Else
firstPeriodDate = EndDate
End If
Dim months As New List(Of String)
Dim Points As New List(Of Integer)
Do While currentDate < firstPeriodDate
months.Add(currentDate.ToString("MMM"))
Points.Add(0)
currentDate = DateAdd(DateInterval.Month, 1, currentDate)
Loop
For Each period In PointTotals
months.Add(CDate(period.month & "/1/" & period.year).ToString("MMM"))
Points.Add(period.totalPoints)
Next
ViewBag.Months = """" & String.Join(""",""", months.ToArray) & """"
ViewBag.Points = String.Join(",", Points.ToArray)
I think this is a more elegant solution than trying to clean up the list after the loop. The only changes to your code are just before, and in, the For Each Period loop.
Dim PointTotals = db.MemberRewards _
.Where(Function(r) sitewideFilterSelectedMemberIds.Contains(r.memberId) And r.supplier.name <> "AudStandard" And r.transactionDate >= startDate And r.transactionDate <= EndDate) _
.GroupBy(Function(r) New With {r.transactionDate.Value.Month, r.transactionDate.Value.Year}) _
.Select(Function(gr) New With {.month = gr.Key.Month, .year = gr.Key.Year, .totalPoints = gr.Sum(Function(r) r.points)}) _
.OrderBy(Function(gr) gr.year).ThenBy(Function(gr) gr.month)
Dim firstPeriodDate As Date
Dim currentDate As Date = DateAdd(DateInterval.Month, -1, startDate)
If PointTotals.Count > 0 Then
Dim firstPeriod = PointTotals.First
firstPeriodDate = CDate(firstPeriod.month & "/1/" & firstPeriod.year)
Else
firstPeriodDate = EndDate
End If
Dim months As New List(Of String)
Dim Points As New List(Of Integer)
Do While currentDate < firstPeriodDate
months.Add(currentDate.ToString("MMM"))
Points.Add(0)
currentDate = DateAdd(DateInterval.Month, 1, currentDate)
Loop
Dim thisPeriodDate As Date
Dim previousPeriodDate As Date = currentDate
For Each period In PointTotals
thisPeriodDate = CDate(period.month & "/1/" & period.year)
Do While DateDiff(DateInterval.Month, previousPeriodDate, thisPeriodDate) > 1
months.Add(previousPeriodDate.ToString("MMM"))
Points.Add(0)
previousPeriodDate = DateAdd(DateInterval.Month, 1, previousPeriodDate)
Loop
months.Add(thisPeriodDate)
Points.Add(period.totalPoints)
previousPeriodDate = DateAdd(DateInterval.Month, 1, previousPeriodDate)
Next
ViewBag.Months = """" & String.Join(""",""", months.ToArray) & """"
ViewBag.Points = String.Join(",", Points.ToArray)
It sounds like that in your code to add missing months you used the .Add method. You would need to use months.Insert(position, CDate(....)) and Points.Insert(position, 0) where position is the correct index to insert the month in the correct order.
I could give you exact commands but you didn't include the cleanup code you referenced in the question.
There's a lot of approaches that you can take to solve this, I'll offer a DB one.
Since you're connecting to a database to pull your data, you can also do your summations/groupings on the DB side.
You can do this in 3 steps:
1) get a distinct list of all your months and store them in a temp table
2) create your summations by month, and store them in another temp table
3) left join step 1 on step 2 (using month as join criteria), order in whatever order you care about, and now you have all your months.
There are a lot of ways to implement this on the SQL side, the approach above was just one I thought would be easy to follow.

Padright in combo box displaymember

I have the following 2 segments of code which populates my combo box but the First Name column obviously is a squiggly one since surnames are various lengths. How could I use something like padright to align the first name column? I have other code using a binding source method but it seems a bit long winded & I'd like to improve on that for all the combos I still have to create.
If RadioButton1.Checked Then
strSQL = "select *, Surname + ' ' + First_Name as Name from tblCompetitors order by Surname, First_Name"
cboData()
End If
Public Sub cboData()
Dim dt As New DataTable
Using conn As New SqlClient.SqlConnection(connString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Using com As SqlCommand = New SqlCommand(strSQL, conn)
Dim dr As SqlDataReader = com.ExecuteReader()
'Dim dt As DataTable = New DataTable
dt.Load(dr)
' as an example set the ValueMember and DisplayMember'
cboFindCompetitor.ValueMember = "Competitor_Idx"
cboFindCompetitor.DisplayMember = "Name"
'Set combobox’s datasource to datatable dt
cboFindCompetitor.DataSource = dt
End Using 'com
End Using 'conn
cboFindCompetitor.SelectedIndex = -1
End Sub
After some fiddling I came up with this solution. It works well on my machine with +- 3000 records in the table
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
If RadioButton1.Checked Then
strSQL = "select Competitor_Idx, Surname as Value1, First_Name as Value2 from tblCompetitors order by Value1, Value2"
cboData(25)
End If
End Sub
Public Sub cboData(z As Integer)
Dim dt As New DataTable
Using conn As New SqlClient.SqlConnection(connString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Using com As SqlCommand = New SqlCommand(strSQL, conn)
Dim dr As SqlDataReader = com.ExecuteReader()
'Dim dt As DataTable = New DataTable
dt.Load(dr)
dt.Columns.Add("Name", GetType(String))
' as an example set the ValueMember and DisplayMember'
cboFindCompetitor.ValueMember = "Competitor_Idx"
cboFindCompetitor.DisplayMember = "Name"
For Each row In dt.Rows
row.item("Name") = row.item("Value1").padright(z) + row.item("Value2")
Next
'Set combobox’s datasource to datatable dt
cboFindCompetitor.DataSource = dt
End Using 'com
End Using 'conn
cboFindCompetitor.SelectedIndex = -1

Can I Compare the day name with the date Entity Framework 6

I am working on news function. News model contains publishing date....
Is there a way to filter my record from db on the base of Publishing Date's day name such as in controller action:
var data1 = db.News.Where(x => x.PublishingDate >= DateTime.Now
&& x.PublishingDate.Day == (int)DayOfWeek.Sunday);
ViewBag.SundayNews = data1;
Or if there is another way around or any reference.
Try this solution: http://c-sharp-snippets.blogspot.ru/2011/12/getting-dayofweek-in-linq-to-entities.html
var firstSunday = new DateTime(1753, 1, 7);
var filtered = from e in dbContext.Entities
where EntityFunctions.DiffDays(firstSunday, e.SomeDate) % 7 == (int)DayOfWeek.Monday
select e;
firstSunday stores the minimal value for MS SQL DATETIME type.

Drop-down list not populating other controls

I am a complete newb to webapps but here goes.
I have web form with a drop-down list that populates a list of holiday resorts from a database procedure. That bit works fine. When I select an item from the list I need to populate a listbox with hotels specific to that resort.
This bit I am having trouble with, the list does populate if I click off the drop-down list onto a calendar control on the form.
Question: how do I get it to populate the list after I clcik on the value from the drop-down list?
Thanks
Here is the code by the way:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
Me.Calendar1.SelectedDate = Now()
Me.DropDownList1.Items.Clear()
Dim connStr As String = Web.Configuration.WebConfigurationManager.ConnectionStrings("ITC").ConnectionString
Dim conn As New SqlClient.SqlConnection(connStr)
conn.Open()
Dim sqlProducts As String = "<<sql_string>>"
Dim da As New SqlDataAdapter(sqlProducts, conn)
Dim ds As New DataSet()
da.Fill(ds, "Products")
DropDownList1.DataTextField = "Rcode"
DropDownList1.DataValueField = "Rcode"
DropDownList1.DataSource = ds.Tables("Products")
DropDownList1.DataBind()
ds.Dispose()
da.Dispose()
conn.Close()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Me.ListBox1.Items.Clear()
Me.ListBox2.Items.Clear()
Dim connStr As String = WebConfigurationManager.ConnectionStrings("ITC").ConnectionString
Dim conn As New SqlConnection(connStr)
conn.Open()
Dim sqlProducts As String = "sql_string '" & Me.DropDownList1.Text & "'"
Dim da As New SqlDataAdapter(sqlProducts, conn)
Dim ds As New DataSet()
da.Fill(ds, "Products")
ListBox1.DataTextField = "accommDescription"
ListBox1.DataValueField = "accommCode"
ListBox1.DataSource = ds.Tables("Products")
ListBox1.DataBind()
ds.Dispose()
da.Dispose()
conn.Close()
ListBox1.Focus()
End Sub

Resources