Save row colour after closing form - vb.net

I got this for saving all data when closing the form.
Public Class Form1
Dim table As New DataTable("Table")
ReadOnly p As String = Path.Combine("C:\test.xml")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
If Not File.Exists(p) Then
table.Columns.Add("Company", Type.GetType("System.String"))
table.Columns.Add("Date", Type.GetType("System.DateTime"))
table.Columns.Add("Code", Type.GetType("System.String"))
table.Columns.Add("Position", Type.GetType("System.String"))
table.Columns.Add("Note", Type.GetType("System.String"))
table.Columns.Add("Solved", Type.GetType("System.DateTime"))
Else
table.ReadXml(p)
End If
DataGridView1.DataSource = table
End Sub
I was using this for mark solved row:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.PaleGreen
DataGridView1.CurrentRow.Cells("Solved").Value = DateTime.Now
DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub
And this for "repair solved row" button:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.White
DataGridView1.CurrentRow.Cells("Solved").Value = ""
DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub
The problem is, that my saving doesn't save this coloured row, it's white when I open the form again.
Any idea? I'm really new to this.
Thanks.

The following code should color the rows as described in my comments.
Private Sub ColorRows()
For Each row As DataGridViewRow In DataGridView1.Rows
If (Not row.IsNewRow) And (row.Cells("Solved").Value IsNot DBNull.Value) Then
row.DefaultCellStyle.BackColor = Color.PaleGreen
End If
Next
End Sub
You could call this code in the forms Load event right after the data has been loaded into the grid. Something like…
….
DataGridView1.DataSource = table
ColorRows()
Edit...
After some testing, it appears that when the code is setting the "Solved" value to an empty string, in the Button4_Click event with...
DataGridView1.CurrentRow.Cells("Solved").Value = ""
This is setting a default min Date value as you noted in the xml file.
Change this line of code to...
DataGridView1.CurrentRow.Cells("Solved").Value = DBNull.Value
It should work as expected then.
Below is the complete code I used to test this.
Dim table As New DataTable("Table")
ReadOnly p As String = Path.Combine("D:\Test\XML\_test_100.xml")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
If Not File.Exists(p) Then
table.Columns.Add("Company", Type.GetType("System.String"))
table.Columns.Add("Date", Type.GetType("System.DateTime"))
table.Columns.Add("Code", Type.GetType("System.String"))
table.Columns.Add("Position", Type.GetType("System.String"))
table.Columns.Add("Note", Type.GetType("System.String"))
table.Columns.Add("Solved", Type.GetType("System.DateTime"))
Else
table.ReadXml(p)
End If
DataGridView1.DataSource = table
ColorRows()
End Sub
Private Sub ColorRows()
For Each row As DataGridViewRow In DataGridView1.Rows
If (Not row.IsNewRow) And (row.Cells("Solved").Value IsNot DBNull.Value) Then
row.DefaultCellStyle.BackColor = Color.PaleGreen
End If
Next
End Sub
Private Sub btnWriteToXML_Click(sender As Object, e As EventArgs) Handles btnWriteToXML.Click
table.WriteXml(p, XmlWriteMode.WriteSchema)
End Sub
Private Sub btnSolved_Click(sender As Object, e As EventArgs) Handles btnSolved.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.PaleGreen
DataGridView1.CurrentRow.Cells("Solved").Value = DateTime.Now
'DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub
Private Sub btnRepairSolved_Click(sender As Object, e As EventArgs) Handles btnRepairedSolved.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.White
DataGridView1.CurrentRow.Cells("Solved").Value = DBNull.Value
'DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub

Related

How to update an Access DB from a DataGridView in Visual Basic

I am creating an inventory application which runs off of an Access DB in visual studio, using visual basic. I can populate my data grid view just fine, but when I try to add new information into the data grid view, it does not number correctly and it does not append my database.
I have tried binding and updating using the table adapter.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Here is my code:
Public Class Form1
Private Sub enterbtn_Click(sender As Object, e As EventArgs) Handles enterbtn.Click
If username.Text = "Tanner" And password.Text = "bmis365" Then
GroupBox1.Visible = False
Else
MsgBox("Incorrect Username or Password, please try again.")
username.Clear()
password.Clear()
username.Focus()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.CurrentCell = Nothing
'This line of code loads data into the 'Database1DataSet.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is where my new info is to be appended into the database, once the button is clicked.
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Private Sub searchbtn_Click(sender As Object, e As EventArgs) Handles searchbtn.Click
'The Following Code is from https://social.msdn.microsoft.com/Forums/vstudio/en-US/36c54726-4f49-4e15-9597-7b201ec13ae7/search-in-datagrid-using-textbox-vbnet-without-data-connectivity?forum=vbgeneral
For Each row As DataGridViewRow In DataGridView2.Rows
For Each cell As DataGridViewCell In row.Cells
If Not IsNothing(cell.Value) Then
If cell.Value.ToString.StartsWith(searchbar.Text, StringComparison.InvariantCultureIgnoreCase) Then
cell.Selected = True
DataGridView2.CurrentCell = DataGridView2.SelectedCells(0)
End If
End If
Next
Next
End Sub
End Class
My output initially has 3 rows(numbered 1, 2, and 3) but any that are added through the application have the numbers -1, -2, -3 and so on. Also, when I close the program and restart it, my original rows (1, 2, and 3) are still there from when I entered them in the DB file, but any that were added through my application are gone.
Here is one way to do an Update, as well as a few other common SQL manipulations/operations.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

Parameter Field current value exception was Unhandled

I'm having a problem in my program that when i click the print button it always show up this error Sample error and i don't know what to do now.
this is the code, this is my parameters sample parameters
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CrystalReportViewer1.ShowPrintButton = False
For Each ctrl As Control In CrystalReportViewer1.Controls
If TypeOf ctrl Is Windows.Forms.ToolStrip Then
Dim btnNew As New ToolStripButton
btnNew.Text = "PRINT"
btnNew.ToolTipText = "Print Reciept"
CType(ctrl, ToolStrip).Items.Insert(0, btnNew)
AddHandler btnNew.Click, AddressOf printClick
End If
Next
End Sub
Private Sub printClick(sender As Object, e As EventArgs)
Dim PrintDialog As New PrintDialog
If PrintDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
CrystalReport11.PrintOptions.PrinterName = PrintDialog.PrinterSettings.PrinterName
CrystalReport11.PrintToPrinter(1, False, 0, 0) 'this is where the error coming up'
Transact()
End If
End Sub
Private Sub btnSlip_Click(sender As Object, e As EventArgs) Handles btnSlip.Click
Dim reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
reportDocument = New CrystalReport1
reportDocument.Refresh()
reportDocument.SetDataSource(dt)
reportDocument.SetParameterValue(0, ComboBox2.Text)
reportDocument.SetParameterValue(1, TextBox1.Text)
Form2.CrystalReportViewer1.ReportSource = reportDocument
Form2.ShowDialog()
Form2.Dispose()
Form2.WindowState = FormWindowState.Maximized
End Sub

How to Drag And Drop selected rows between DataGridViews

I need to implement drag and drop of the selected rows from one grid to the other:
my code:
datagridview1
Private Sub datagridview1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles datagridview1.MouseDown
Dim info As DataGridView.HitTestInfo = Me.datagridview1.HitTest(e.X, e.Y)
If info.Type = DataGridViewHitTestType.Cell And e.Button = Windows.Forms.MouseButtons.Left Then
Me.datagridview1.DoDragDrop(datagridview1.SelectedRows.Cast(Of DataGridViewRow).OrderBy(Function(r) r.Index).ToArray, DragDropEffects.All)
End If
End Sub
datagridview2
Private Sub datagridview2_DragEnter(sender As Object, e As DragEventArgs) Handles datagridview2.DragEnter
e.Effect = DragDropEffects.All
End Sub
Private Sub datagridview2_DragDrop(sender As Object, e As DragEventArgs) Handles datagridview2.DragDrop
Try
Dim Rows() As DataGridViewRow = DirectCast(e.Data.GetData(GetType(DataGridViewRow())), DataGridViewRow())
For Each row As DataGridViewRow In rows
MsgBox(row.Cells("ID").Value)
Next
Catch ex As Exception
End Try
End Sub
but there is an error in conversion.
any ideas?
Try sending a copy of the selected rows instead:
Dim dgrCopy(datagridview1.SelectedRows.Count - 1) As DataGridViewRow
datagridview1.SelectedRows.CopyTo(dgrCopy, 0)
Me.datagridview1.DoDragDrop(dgrCopy.OrderBy(Function(r) r.Index).ToArray, DragDropEffects.All)

Vb.net Editing DatagridView

I created a simple program where I can search through a database table. Add data and remove data through a button. Now I want to be able to update the data within the datagrid view however i am getting the classic error: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
I have the primary key in the data grid that is not attached to anything in the vb.net program nor in the database at this time. I am not sure what I am missing.
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=Inventory;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, First_Name, Last_Name, Item FROM Inventory_Details", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
'Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
DataGridView1.AllowUserToAddRows = True
DataGridView1.AllowUserToDeleteRows = True
DataGridView1.[ReadOnly] = False
adap.InsertCommand = builder.GetInsertCommand()
' adap.UpdateCommand = builder.GetUpdateCommand()
adap.UpdateCommand = builder.GetUpdateCommand
adap.Fill(dt)
InventoryDetailsBindingSource.DataSource = dt
DataGridView1.DataSource = InventoryDetailsBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
InventoryDetailsBindingSource.Filter = String.Format("First_Name Like '%{0}%'", TextBox1.Text)
Else
InventoryDetailsBindingSource.Filter = String.Empty
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
MessageBox.Show("Saved successfully")
Catch ex As Exception
MessageBox.Show("Error updating database")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
adap.Update(dt)
DataGridView1.[ReadOnly] = True
Button2.Enabled = False
End Sub
End Class
Actually I was incorrect. I did not have a primary key set on my database. I dropped my table - recreated with primary key.

open selected row in datagridview to edit in Another form

I am using vb.net designer to connect to access database .
On my Form1 I have a DataGridView And Two Button For Add And Edit
I Make Form2 To Add Data Into Database And Worked OK ..
Imake Form3 Wiht Same form2 Content
Now I need When i selcet row in DataGridView And Clic Edit Button The data of selected row show on form3 for Edit it
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.SalesTableAdapter.Fill(Me.OrdersDataSet.sales)
Me.DateTimePicker1.Value = Date.Today
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
SalesBindingSource.Filter = String.Format("date = '{0}'", DateTimePicker1.Value.ToShortDateString())
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.Show()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Form3.Show()
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub SalesDataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles SalesDataGridView.CellContentClick
End Sub
End Class
You need to approach this in a modal/dialog way. You only need one form for both add and edit.
Add/Edit form
Add a parameterized constructor to the form.
Public Sub New(row As DataRowView)
Me.InitializeComponent()
'Me.ctlAge: NumericUpDown control.
'Me.ctlBirthday: DateTimePicker control.
'Me.ctlName: TextBox control.
If (row Is Nothing) Then
'Add mode, set default values:
Me.ctlAge.Value = 0
Me.ctlBirthday.Value = Date.Now
Me.ctlName.Text = String.Empty
Else
'Edit mode, set current values:
Me.ctlAge.Value = CDec(row.Item("AGE"))
Me.ctlBirthday.Value = CDate(row.Item("BIRTHDAY"))
Me.ctlName.Text = CStr(row.Item("NAME"))
End If
End Sub
You also need an accept button and a cancel button.
Friend Sub btnAcceptClicked(sender As Object, e As EventArgs) Handles btnAccept.Click
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Friend Sub btnCancelClicked(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Main form
Add method:
Private Sub btnAddClicked(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
Using f As New AddOrEditForm(CType(Nothing, DataRowView))
If (f.ShowDialog() = Windows.Forms.DialogResult.OK) Then
Dim view As DataView = TryCast(Me.SalesDataGridView.DataSource, DataView)
If (view Is Nothing) Then
Throw New InvalidCastException()
End If
Dim viewRow As DataRowView = view.AddNew()
viewRow.EndEdit()
viewRow.Item("AGE") = f.ctlAge.Value
viewRow.Item("BIRTHDAY") = f.ctlBirthday.Value
viewRow.Item("NAME") = f.ctlName.Text
viewRow.EndEdit()
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Edit method:
Private Sub btnEditClicked(sender As Object, e As EventArgs) Handles btnEdit.Click
Try
Me.SalesDataGridView.EndEdit()
If (Me.SalesDataGridView.SelectedRows.Count > 0) Then
Dim gridRow As DataGridViewRow = Me.SalesDataGridView.SelectedRows(0)
Dim viewRow As DataRowView = TryCast(gridRow.DataBoundItem, DataRowView)
If (viewRow Is Nothing) Then
Throw New InvalidCastException()
End If
Using f As New AddOrEditForm(viewRow)
If (f.ShowDialog() = Windows.Forms.DialogResult.OK) Then
viewRow.BeginEdit()
Try
viewRow.Item("AGE") = f.ctlAge.Value
viewRow.Item("BIRTHDAY") = f.ctlBirthday.Value
viewRow.Item("NAME") = f.ctlName.Text
viewRow.EndEdit()
Catch ex As Exception
viewRow.CancelEdit()
Throw ex
End Try
End If
End Using
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub