Display Date VC2012 windows forms - winforms

I'm trying to display the current time on an app i'm developing.
I have a label and a timer control and the following code:
Private Sub Timer1_Tick_1(sender As Object, e As EventArgs) Handles Timer1.Tick
Label16.Text = TimeOfDay
End Sub
Shouldn't this work? I've been searching and it should work, is there a way for it to display the date as well?
Thanks for the help,
Bruno

As simple as this
Label16.Text = DateTime.Now.ToString()
Other variations
Label16.Text = DateTime.Today.ToShortDateString() ' just the today date in short format'
Label16.Text = DateTime.Now.ToShortTimeString() ' just the current time in short format'

Related

Show selected index of datagridview on another form using pre-defined textboxes?

First time posting and is a beginner in vb.net data-basing.
I've got a datagridview on form1 which gets populated through a datasource. (access database from file). On form1 i have the datagridview to show all of my "projects and details. I can either double click a cell or click a button to go to the Edit Projects form. On the Edit Projects form i have placed the pre-defined details from the datasource.(textboxes, checkboxes etc. )
Now my problem is, when i go to the Edit Projects form, it does not pull through the selected row's details, but the default first row details.
On form load the adaptor gets filled like this.
Me.ProjectsTableAdapter.Fill(Me.ProjectsXDataSet.Projects)
When i go to Edit Form
Public Sub Editproject()
'Disable form 1 to lock interface while editing a project
'
Me.Enabled = False
Form2.Show()
End Sub
Public Sub CellDoubleClick()
Form2.TextBox1.Text = ""
Form2.TextBox2.Text = ""
Form2.DataGridView1.DataSource = Nothing
Dim filenme As String = Form2.ProjectTextBox.Text & ".txt"
If My.Computer.FileSystem.FileExists(filenme) = True Then
Form2.TextBox2.Text = My.Computer.FileSystem.ReadAllText(Form2.ProjectTextBox.Text & ".txt")
Dim pathfolder As String = Form2.TextBox2.Text
Dim stringpath As String = pathfolder & "\" '
Form2.DataGridView1.DataSource = Fileinfo_To_DataTable(pathfolder)
Else
' MsgBox("Please add a workfolder")
End If
Try
Dim project As String = Form2.ProjectTextBox.Text
Dim filenme2 As String = project & " notes.txt"
Form2.TextBox1.Text = My.Computer.FileSystem.ReadAllText(filenme2)
Catch ex As Exception
End Try
End Sub
I've tried playing around with updating the tableadaptor but i can not figure anything out.
Launch code added:
Private Sub EditProjectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditProjectToolStripMenuItem.Click
Editproject()
CellDoubleClick()
End Sub
OR
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
Editproject()
CellDoubleClick()
End Sub
See image....I double click the selected row im the datagridvew, which opens the editing form(form2). but with the linked textboxes it shows row 1(0)'s values
enter image description here

Connecting and Updating to Database through VB.NET "Select command property has not been ... "

I am using this guide to update a value in a database through VB.NET and really struggling to get it to work.
I am trying to add 1 to a particular cell in the database. The grid that I am using updates with the value, but the database itself doesn't change. Using different tutorials (and loads of other StackOverflow questions) I have changed the code from the original but nothing seems to work.
Each time I click the button that should trigger the addition, I get this error message.
"The select command property has not been initialized before calling fill"
If anyone could tell me what is going wrong or point me in the direction that I should go in, it would be much appreciated. Thanks.
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim senderGrid = DirectCast(sender, DataGridView)
Dim OleDbDataAdapter As New OleDb.OleDbDataAdapter
If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso
e.RowIndex >= 0 Then
' If addition
If e.ColumnIndex = 3 Then
Try
'from microsoft tut
ProjectDatabaseDataSet.Tables(0).Rows(e.RowIndex).Item("ProductStock") = ProjectDatabaseDataSet.Tables(0).Rows(e.RowIndex).Item("ProductStock") + 1
OleDbDataAdapter.Fill(ProjectDatabaseDataSet.Product)
OleDbDataAdapter.Update(ProjectDatabaseDataSet.Product)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If

Combining Formatting and Databinding from the database

I have a set of labels in a DataRepeater. The labels get their values from a table in a SQL database (Let say GetSQLResults gets the data from SQL database and returns a DataTable).
Dim salesDataTable As DataTable = GetSQLResults()
And for the binding
SalesLabel.DataBindings.Add("Text", salesDataTable , "Sales")
Where SalesLabel is a label in the form and "Sales" is the name of the column in the database.
What I want to do is to apply let say US money formatting to this Sales value that comes from the database. I don't know how to combine formatting information with the command that I wrote above for DataBinding. It is a Windows Form application and I am using VB .Net. Any help will be appreciated.
The Binding class has a FormatString property which you should be able to feed the standard or custom format string you desire.
I think perhaps something like:
Dim salesBinding As Binding = new Binding("Text", salesDataTable , "Sales")
salesBinding.FormatString = "C"
SalesLabel.DataBindings.Add(salesBinding)
Would do the trick.
I tried this based on nkvu answer and a post at http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/c860168f-46e5-4786-a68d-ac69c6a7a248/
Dim WithEvents salesBinding As Binding
salesBinding = New Binding("Text", salesDataTable , "Sales")
SalesLabel.DataBindings.Add(salesBinding)
Private Sub salesBinding_Format(ByVal sender As Object, ByVal e As System.Windows.Forms.ConvertEventArgs) Handles salesBinding .Format
If e.Value Is DBNull.Value Then
Else
e.Value = Format(e.Value, "c")
End If
End Sub
This did the trick for me.

Linq-to-SQL SubmitChanges not updating physical database

I am new here and only signed up because I desperately need the solution to my problem. I have a VB.NET project that is using a local .MDF file that I have imported into my project. The primary keys are intact so I know that isn't my issue.
I am using Linq-to-SQL to query the database and make changes. On my main form I use a Data Grid View that is populated by a query. I am having an issue with my insert where the query works fine and the DGV gets updated with newly created data, but when I call SubmitChanges() the changes do not get saved to the actual physical database. I am not sure what I am missing or doing wrong.
Here is my code to better assist your educated answer.
Public Class frmCell_Leader
'Reference DataContext
Private db As New MarquardtClassesDataContext()
Private Sub frmCell_Leader_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FillProductionGrid()
PrepareInsertFields()
End Sub
Private Sub FillProductionGrid()
''''''''''''''''''''''''''''''''''
'E.Salce Last Modified 11.29.2012
'Comments: Working
''''''''''''''''''''''''''''''''''
'Populate DGV
Dim query = From marq In db.tblProductivities
Select
marq.PartNum, marq.Produced, marq.Packed, marq.Issue, marq.StationNum, _
marq.PlanDownTime, marq.UnplannedDownTime, marq.CurDate
dgvProduction.DataSource = query
End Sub
Private Sub PrepareInsertFields()
''''''''''''''''''''''''''''''''''
'E.Salce Last Modified 11.29.2012
'Comments: Working
''''''''''''''''''''''''''''''''''
'Fill Planned Downtime Combo Box
Dim PlannedQuery = From planned In db.tblPlannedDownTimes
Select planned.Plan_ID, planned.Description, planned.Active
Where Active = True
cboPlanned.DataSource = PlannedQuery
cboPlanned.DisplayMember = "Description"
cboPlanned.ValueMember = "Plan_ID"
'Fill UnPlanned Downtime Combo Box
Dim UnPlannedQuery = From unplanned In db.tblUnplannedDownTimes
Select unplanned.Unplan_ID, unplanned.Description, unplanned.Active
Where Active = True
cboUnplanned.DataSource = UnPlannedQuery
cboUnplanned.DisplayMember = "Description"
cboUnplanned.ValueMember = "UnPlan_ID"
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
'Add the new Production to database
'Create an productivity object
Dim marqpro As New tblProductivity With {
.PartNum = CShort(txtPartNumber.Text),
.Produced = CShort(txtProduced.Text),
.Packed = CShort(txtPacked.Text),
.Issue = txtIssue.Text,
.PlanDownTime = CShort(cboPlanned.SelectedValue),
.UnplannedDownTime = CShort(cboUnplanned.SelectedValue),
.CurDate = Date.Today}
'insert newly created data
Try
'Submit changes too database
db.tblProductivities.InsertOnSubmit(marqpro)
db.SubmitChanges()
db.Refresh(Data.Linq.RefreshMode.KeepCurrentValues, marqpro)
'Refresh DGV
FillProductionGrid()
MessageBox.Show("Data added successfully")
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
End Sub
End Class
Perhaps you have an .mdf file in your project that is getting copied to the bin/debug folder everytime you build.
Why isn't my SubmitChanges() working in LINQ-to-SQL?

Trouble reading database records into memory variables in VB 2010

I followed an example on stackoverflow about how to read database records into variables. This is the first time doing this and I feel that I'm close but I'm baffled at this point about the problem.
Here is the link I am referring to:
Visual Basic 2010 DataSet
My code is shown below.
Public Class Form1
' DataSet/DataTable variables
Dim testdataDataSet As New DataSet
Dim dttestdataDataTable As New DataTable
Dim datestdataDataAdapter As New Odbc.OdbcDataAdapter
' Variables for retrieved data
' Dim sSpeed As String = ""
' Dim sFuelprice As String = ""
Dim sSpeed As Integer
Dim sFuelprice As Integer
'Connect to the database
''
'Fill DataSet and assign to DataTable
datestdataDataAdapter.Fill(TestdataDataSet , "TestdataDataSet")
dttestdataDataTable = TestdataDataSet.Tables(0)
'Extract data from DataTable
' Rows is the row of the datatable, item is the column
sSpeed = dtTestdataDataTable.Rows(0).Item(0).ToString
sFuelprice = dtTestdataDataTable.Rows(0).Item(1).ToString
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
result.Text = Val(miles.Text) * sSpeed * sFuelprice
End Sub
End Class
Basically, I am getting declaration errors and I don't understand why since the example I was following clearly declared them. I'm connecting to an Access DB called "testdata.mdb" which contains only 1 record with two fields that I want to use throughout the program. The exanple said to dim the variables for each field as strings but this created more dim errors so I made them into integers and remarked out the original dim statements in the meantime (since they're going to be used in calculations.) The dataadapter and datatable variables also are getting flagged for not being declared when they were earlier in the program. I know this must be a simple thing to fix but I'm just not seeing it.
The form is just a simple thing where the user types in a number and a result is produced by using the numbers read in from the database. In short, I want to be able to do simple calculations with a database within a program and the dim statement thing is getting in the way.
If someone can please clarify what I should do, that would be very much appreciated. Thanks!
When you're trying to learn new technology, it's usually best to work from the outside in. The "outside-most" object in your case seems to be an OdbcConnection object.
Public Class Form1
Const connectionString as String = "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\bin\Northwind.mdb"
Dim connection As New OdbcConnection(connectionString)
connection.Open()
connection.Close()
end Class
Resolve errors at that level first. Then add a declaration for the data adapter--only for the data adapter--and resolve any errors with that. Repeat until you finish your class.
See OdbcConnectionString, and refer to the connection string web site if you need to.
I apologize for the delay in writing the answer to close off this question and sum it up.
In my case, it dataset is a one row database called testdata and contains 20 fields.
The solution that worked is as follows:
Immediately after the form1_load event, the variables can be immediately written after the dataadapter line:
Me.TestdataTableAdapter.Fill(Me.fooDataSet.testdata)
speed = Me.fooDataSet.testdata(0).speed
fuelprice = Me.fooDataSet.testdata(0).fuelprice
mpg = Me.fooDataSet.testdata(0).mpg
Then just DIM the variables to whatever you want them to be (in this case, speed is an integer, fuelprice is a decimal and MPG is a decimal) right after the PUBLIC CLASS statement at the top of your form's code.
You can then manipulate the variables in calculations after a button click as such:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
fuelcost = CDec((miles.Text/ mpg) * fuelprice)
txtfuelcost.Text = fuelcost.ToString
End Sub
Thank you all for your responses!

Resources