Setting the value of cell in datagridview not working in form load - vb.net

This is my code for setting the value in datagridview cell:
For i = 0 To dvJOBranch.Rows.Count - 1
dvJOBranch.Rows(i).Cells.Item("XS").Value = 0
dvJOBranch.Rows(i).Cells.Item("S").Value = 0
dvJOBranch.Rows(i).Cells.Item("M").Value = 0
dvJOBranch.Rows(i).Cells.Item("L").Value = 0
dvJOBranch.Rows(i).Cells.Item("XL").Value = 0
Next
Its working in button event, shown form event, but not in form load, and there are no errors.
My question is why it does not work in form load?

My guess is that you are using the DataGridView.AutoGenerateColumns functionnality and even if you set the DataSource property, the DatagridView won't create columns until the grid is displayed.
It could explain why it's not working in formload (grid is not initialized yet) and it works after (with shown event for example).
So it's possible that:
you try to access items that do not exist yet (but the code should raise an exception)
or you access valid rows or columns, but they are replaced when the grid is displayed the first time or bound again to a data source, and so your code has no effect (probably your case since you do not mention an exception).
Using form_shown is maybe a possible workaround, but I recommend you to use the DataGridView.DataBindingComplete event which is more especially designed to handle this situation.
See also these related issues (same cause):
Why DataGridColumn not getting removed from DataGridView
Datagirdview and tabcontrol issue
Strange issue with a datagridview and a tabcontrol C#
DataGridView has no columns

Related

Entity with Winforms / bindingsource - can't save user input from controls

I have a winforms program I am migrating to entity (EF5). The edit works okay. The add does not. The basic workflow is user can either add or edit an object. There is a list of comboboxes, text boxes, etc on screen for the user to input.
I have the entity bound to a binding source. I have the textbox bound to the bindingsource.
Add functionality looks like this.
If (mViewAddEdit = ViewAddEditEnum.Add) Then
Dim ps As New RADS.PHANTOM_SESSION
Me.bsPhantom.DataSource = db.PHANTOM_SESSION.Add(ps)
Me.EdtMuscleWater.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.bsPhantom, "MUSCLE_OR_WATER", True, DataSourceUpdateMode.OnValidation)) ' etc
End If
So that seems okay, but when user clicks ok button (to save).
drvPhantom = TryCast(Me.bsPhantom.Current, RADS.PHANTOM_SESSION)
' examining the object shows nothing bound.
If mViewAddEdit = ViewAddEditEnum.Add Then
db.PHANTOM_SESSION.Add(drvPhantom)
db.SaveChanges()
End If
The issue arose from the form blocking validation.
Me.AutoValidate was set to disable. So this blocked the binding source from updating even with a call to Me.Validate()
Also since I found it so hard. This is how to Add or Edit - controls bound to binding source using Entity EF5.
If (mViewAddEdit = ViewAddEditEnum.Add) Then
Me.bsPhantom.DataSource = New PHANTOM_SESSION
SetPhantomDataBindings()
Else
Dim query = From ps In db.PHANTOM_SESSION Where (ps.PHNTM_SESSION_NO = CDbl(mPhntmSessionNum))
bsPhantom.DataSource = query.ToList() ' resize occurs here
SetPhantomDataBindings()
...
End If
The other thing is if you are programmatically writing to the text box, ie textbox1.text = "foo" you must also update the underlying object.
CType(Me.bsPhantomBlock.Current, RADS.PHANTOM_BLOCK).OTHER_CORRECTION = CDec(val)
Here we are casting the current object of the binding source to its type (PHANTOM_BLOCK) then setting the field "OTHER_CORRECTION" to val.
Updating the binding source does not work as it causes all inputted user data to be thrown away. For example there are 5 text boxes (a,b,c,d,e). user enters 1,2,3,4,5 into those. The 5th is handled by bindingsource Write: textbox1.DataBindings(0).WriteValue - this will update the 5th field (e),but causes a,b,c,d to be blank as the are reverting to stored value. This is my experience anyway.

Losing cell data when datagridview gets focus

I know I need to provide some code, but I'm not sure what I should show, so please suggest if you can.
I have a bound datagridview on a Windows form. After the form loads and the datagridview gains focus (on mouse click), the first row (and a specific column) loses it's data, changing the cell's state to dirty. It doesn't matter where I click to bring the dgv into focus, that row/column always goes blank. What event is firing that may trigger that loss of data?
Again, any suggestions as to what code to post would be great. I know that will help answer this question.
Edit #1
This code is an infinite loop, but I'm adding it in response to a comment:
Private Sub dgQCOrders_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles dgQCOrders.CellPainting
If e.RowIndex = 0 And e.ColumnIndex = 9 Then
If e.FormattedValue <> e.Value Then
MsgBox("Changed")
Else
MsgBox("Unchanged")
End If
End If
End Sub
Edit #2:
Private Sub dgQCOrders_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles dgQCOrders.CellPainting
If e.RowIndex = 0 And e.ColumnIndex = 9 Then
If e.FormattedValue <> e.Value Then
Me.txtTest.Text = "Changed"
Else
Me.txtTest.Text = "Unchanged"
End If
End If
End Sub
This test tells me that the new value is null, it is deleting that first record (which I already knew)--still don't know how to fix it!
Edit #3
More explanation:
Currently, the only event I'm handling is form_Load, which fills the dgv using the tableadapter for my (bound) dataset. I then bind the dgv to the binding source.
I know that this error only occurs when the dgv gains focus (I tested this by setting the focus to the dgv when the form loads). I have a series of checkboxes/listboxes/textboxes on this form as well that allows the user to filter the dgv dynamically (back-end, I filter the binding source). If I filter the dgv first, the same row and the same column (their indexes do not change) maintains it's value when I move the focus to the dgv. When I clear the filter, the same row and the same column, loses it's data again.
I did have the _CellStateChanged event firing after a user makes an edit. Currently, it is commented out so the data loss isn't reflected in my dataset.
Additionally, I have another dgv on a different form, bound the exact same way, with the _CellStateChanged event and everything fires and saves correctly. I have gone through the designer coding for both forms, I can't find any setting difference between the two.
I'm losing my mind over here! Any help is GREATLY appreciated!
I decided to recreate the form from scratch and this error is no longer occuring. I have compared the two sets of code and can't find one discrepancy between them. If anyone has this problem in the future, save time and recreate all of the objects related to your dgv.
Maybe I understand that statement within the focus cell is not saved in the database table if U save
this problem I solved
add blank textbox control to your form which contain dgv and named txtFocus
placed it behand dgv and use its properties send to back Or
Evoked by the bottom of the screen so do not show it
then
before save
white then :
txtFocus.Focus()
sendKeys.send("{F2}")
only in this case U can save the data inside last cell changed in dgv
best Reg
Ashraf

Checkbox in a DataGridView column is not getting checked sometimes?

I use this code to check all the check-boxes in a data grid view in VB.NET (2010 - .NET Framework 4.0),
Dim i As Integer
For i = 0 To (DataGridView.Rows.Count - 1)
DataGridView.Rows(i).Cells(0).Value = True
Next
Sometimes when one of the row is selected (not checked but just the entire row is selected) while this code is running, it checks all other check-boxes in the column except the selected one. What is wrong here?
I also try adding this code,
DataGridView.SelectedCells(0).Cells(0).Value = True
Did not work.
Like I said in the comments, the issue is that the box is checked in the datasource, but the GUI hasn't refreshed that cell to reflect it. If you click off of it, the cell should change/refresh to your new value. After you have made your data changes, at the very end you should deselect cells/rows. You can do it by:
Datagridview.ClearSelection()
or
Datagridview.CurrentCell = Nothing 'deselects
You get the idea. This is what has worked for me in the past.

Show Data Grid View specified cell value in Textbox

I am a student programmer who is learning VB. I am trying to make a telephone book type project in VB (Windows Forms). In my project I am using an unbound Data Grid View control. Below the Data Grid View, I have some textboxes which will display the values of the selected row. On the form load event, my program accesses a file and populates the Data Grid View control with values from the file. This works perfectly, but the problem I get is when I use the code:
txtLast.Text = dgvMain.Rows.Item(0).Cells(0).Value
to populate the textbox called txtLast with the value at the specified cell, the textbox doesn't display the value. The program doesn't crash or hang, it simply won't display the value and when I try to edit the textbox, it acts as if the textbox is empty. I have tried using
txtLast.Text = dgvMain.Rows.Item(0).Cells(0).Value.ToString()
as well as trying to refresh my Data Grid View control and the textbox. Nothing has worked so far. When I use a breakpoint to see whether that line of code is executed, the autos window shows me that the line of code is executed and that it sees the value of the specified cell as "Smith". However, when I press F11 to step into the next line, the textbox.text property remains as "" instead of changing to "Smith".
Note: when I manually specify the text through the code (i.e. txtLast.Text = "Test") it will show that text. Also, this problem is not with just one textbox, it is with every textbox that I use (I have 5 textboxes showing various values from the specified row). The weird thing is that out of the 5 textboxes, one of them, the masked textbox which shows the phone number works perfectly with the same line of code. (note it is not a problem only affecting regular textboxes as I have tried using both regular textboxes and masked textboxes, both produce the same problem except for the phone textbox).
Also, I would prefer to keep the Data grid view unbound (not connected to a database) and the textboxes unbound (not connected to the data grid view as a data source) because while browsing the internet I have seen people suggesting to bind the textbox or data grid view, however I do not understand how to do so, and I believe that this can be done without binding to a data source.
Any help is appreciated in trying to figure out why the text doesn't change. Let me know if you need any other info or if part of my explanation is unclear.
Thanks!

Run through all the controls in a form

I have a form and I am running through all the controls in that form.
My code is OK and is get all the controls with all their properties.
So for example I have a TabControl with 2 TabPages and 2 textboxes in each tabPage.
The problem is that for the tabPage that isn't selected , the textboxes' property visible is False, although I have set it to True.
I tried to solve this problem with Control.Select and Control.Focus , but Visible is still False:
Private Sub createXML(ByVal cnt As Control, ByVal elem As XElement)
Try
cnt.Select()
cnt.Focus()
Select Case cnt.Controls.Count
Case Is = 0
'Code here to write XElement to an XDocument
'Check Controls properties
Case Is > 0
For Each childCnt As Control In cnt.Controls
childCnt.Select()
childCnt.Focus()
Dim childElem As New XElement(childCnt.GetType.ToString)
Select Case childCnt.Controls.Count
Case Is = 0
'Code here to write XElement to an XDocument
'Check Controls properties
Case Is > 0
createXML(childCnt, childElem)
End Select
Next
End Select
Any ideas?
Note that I don't know what controls I have to run through each time
Your problem in this case is that a TabControl sets everything to invisble unless they are present in the currently selected tabpage. And when you change tab the controls are set to visible and previous ones dissapeares. So how does the tabcontrol keep track of a control that is manually set to visible false, so that it doesn't light up when the tab is changed? Well the visible property is not really based on a boolean value. It's merely an easy way to interpret it for us programmers. Either you see it or you don't, no rules to keep in mind or settings to mess up. Visible or not simple as that.
So what to do with your issue. Basically, my first thought when I see this is that you want to create a "open the program so it looks the same as when it was closed"-function. Which of course is not working properly at the moment since your parser probably set everything to visible=false, which at previously stated means not visible ever. Hence not showing after Tab control page change when loaded.
So solutions:
1. Add a tag to the controls in the tab control. This way you can look for the tag when saving. If it's there, set the visible property to true. (Easy to understand for you when maintaining in the future)
2. Use reflection to get the actual visible state. Look at SO thread and read about reflection: Using control.Visible returns False if it's on a tab page that is not selected (Not so easy to understand when maintaining in future)