DataGridView bound to DataTable is not showing - vb.net

I am trying to show a DataGridView in a form that is bound to a DataTable, but it's not showing up. I was doing this using a C1TrueDBGrid and that was working...I decided to switch to using a DataGridView due to some complications with the TrueDBGrid. Can anyone help me figure out why nothing is showing?
In the form I declare these:
Public binData As DataSet
Friend WithEvents dgvData As System.Windows.Forms.DataGridView
The binData is filled with tables created via a separate calculation routine. Then this is the form load event:
'create a tab page and add data grid view for every table in the set
For i = 0 To binData.Tables.Count - 1
Dim tabPage As C1.Win.C1Command.C1DockingTabPage = New C1.Win.C1Command.C1DockingTabPage
tabPage.Text = binData.Tables(i).TableName
tabContent.TabPages.Add(tabPage)
Dim dgvData = New System.Windows.Forms.DataGridView
Dim binding As New BindingSource
binding.DataSource = binData.Tables(i)
With dgvData
.Dock = DockStyle.Fill
.AllowUserToOrderColumns = False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomLeft
.DataSource = binding
.AutoGenerateColumns = True
End With
tabPage.Controls.Add(dgvData)
Next 'DataTable In binData.Tables
When the form loads, the tab pages are there and labeled as expected, but they look empty (no table).
I did try instead setting the DataSource to the DataSet called binData (as opposed to a specific table), and then setting dgvData's DataMember property to the name of the specific table I want to display in it...that made no difference.
Note: I need to be able to do this programmatically at runtime as opposed to using the visual designer because I do not know the exact number of grids I need until the form loads with a particular dataset - the dataset it gets can have a different number of tables depending on what the user wants.

Here's some rough code to add dgvs to a flow panel:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static dgvCount As Integer
dgvCount += 1
Dim dgvNew As New DataGridView
dgvNew.Width = DataGridView1.Width
dgvNew.Height = DataGridView1.Height
dgvNew.Name = "dgv" & dgvCount
' clone other properties as need
FlowLayoutPanel1.Controls.Add(dgvNew)
Debug.Print(FlowLayoutPanel1.Controls(FlowLayoutPanel1.Controls.Count - 1).Name)
End Sub
Starts with one dgv - DataGridView1 as the model for properties. Anchoring is not working in the flow panel so some custom code may be need to change width.
Flow panel doesn't scroll so may not be the best choice - look into TableLayout as a possibility. TabControl is another option.

OK, well it turns out there was nothing wrong with what I was doing. The issue turned out to be in one line of code that has nothing to do with binding the DGV's datasource or anything.
ComponentOne has a control called a ThemeController in which you can set themes for your forms and the controls within. I had a line of code to set the theme for dgvData to my default application theme (which sets visual style and details regarding colors, fonts, etc.). For whatever reason, THAT was rendering my grid non-visible. I will be logging a ticket with them.

Related

ComboBox shows the first item when loaded into new form VB.Net

I have two forms which are connected, the first one has a datagridview(DGV) that will show list of staff.
When I double click the row the data from the FGV will transfer into second form for user to edit the data. Each column from the DGV will insert at textbox combobox etc.
But the combobox on second form are using database when I double click the DGV; the others is fine but for combobox it will show the first data in database.
This is the code for the double click on the first form:
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
Dim frmEdit As New Edit
frmEdit.lblEENo.Text = DataGridView1.CurrentRow.Cells(1).Value.ToString
frmEdit.txtName.Text = DataGridView1.CurrentRow.Cells(2).Value.ToString
frmEdit.txtAge.Text = DataGridView1.CurrentRow.Cells(3).Value.ToString
frmEdit.lblAgeCategory.Text = DataGridView1.CurrentRow.Cells(4).Value.ToString
frmEdit.txtGender.Text = DataGridView1.CurrentRow.Cells(5).Value.ToString
frmEdit.cbEthnicity.Text = DataGridView1.CurrentRow.Cells(6).Value.ToString
frmEdit.cbGrade.Text = DataGridView1.CurrentRow.Cells(7).Value.ToString
frmEdit.cbCategory.Text = DataGridView1.CurrentRow.Cells(8).Value.ToString
frmEdit.cbDepartment.Text = DataGridView1.CurrentRow.Cells(9).Value.ToString
frmEdit.cbPosition.Text = DataGridView1.CurrentRow.Cells(10).Value.ToString
frmEdit.txtReporting.Text = DataGridView1.CurrentRow.Cells(11).Value.ToString
frmEdit.DateTimePicker1.Value = DataGridView1.CurrentRow.Cells(12).Value.ToString
frmEdit.DateTimePicker2.Value = DataGridView1.CurrentRow.Cells(13).Value.ToString
If DataGridView1.CurrentRow.Cells(14).Value.ToString = "Y" Then
frmEdit.rbYes.Checked = True
ElseIf DataGridView1.CurrentRow.Cells(14).Value.ToString = "N" Then
frmEdit.rbNo.Checked = True
End If
frmEdit.cbStatus.Text = DataGridView1.CurrentRow.Cells(15).Value.ToString
frmEdit.txtNote.Text = DataGridView1.CurrentRow.Cells(16).Value.ToString
frmEdit.lblMody.Text = tslblLoginAs.Text
frmEdit.ShowDialog()
load_data()
End Sub
This is second form's code for connecting to the database table for the combobox:
Private Sub Edit_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim frmMasterList As New MasterStaff
Dim poscmd As New SqlCommand("SELECT * from MasterPositionList", conn)
Dim posadapt As New SqlDataAdapter(poscmd)
Dim postable As New DataTable
posadapt.Fill(postable)
cbPosition.DataSource = postable
cbPosition.DisplayMember = "PositionName"
Dim depcmd As New SqlCommand("SELECT * from MasterDepartmentList", conn)
Dim depadapt As New SqlDataAdapter(depcmd)
Dim deptable As New DataTable
depadapt.Fill(deptable)
cbDepartment.DataSource = deptable
cbDepartment.DisplayMember = "DeparmentName"
End Sub
The form load event fires too late to populate the combobox. The event is raised almost immediately when you create the form instance in the DataGridView1_CellDoubleClick() method, but the event handler can't actually run until control is returned to the messaging loop, and there's no chance for that to happen until the frmEdit.ShowDialog() line, which is after you have set the combobox values. Therefore the Load event runs after you have populated your desired value and will overwrite that work.
To fix this, move that Load code to the constructor, just after the InitializeComponent() method.
Additionally, since you want to select from the items provided by the database you should look at using the SelectedItem or SelectedValue property, instead of the Text property.
Finally, it's really poor practice to reuse the same connection object throughout an application or form. Yes, database connections are expensive objects to create and manage, but the ADO.Net library already handles this for you. The SqlConnection object you work with in code is a light-weight wrapper over a pool of the more-expensive actual raw connections. When you try to reuse one SqlConnection, you gain efficiency in the cheap thing while losing efficiency in the more expensive thing.
Instead, create (and promptly Dispose()!) a new SqlConnection object every time you need to use the database, and think about reducing connections by reducing round-trips to the database. In this case, you can combine the two SELECT statements into a single string and fill two DataTables in the same database trip:
Private Sub New ' Replaces the current Edit_Load() method
InitializeComponent()
Dim results As New DataSet
'Using block will make sure the connection is closed, **even if an exception is thrown**
' Do NOT(!) try to reuse the connection. Only reuse the connection string.
Using conn As New SqlConnection(connString), _
' Two SELECT queries in one string
cmd As New SqlCommand("SELECT * from MasterPositionList;SELECT * from MasterDepartmentList", conn), _
da As New DataAdapter(cmd)
da.Fill(results)
End Using 'Dispose the database objects as quickly as possible
cbPosition.DisplayMember = "PositionName"
cbDepartment.DisplayMember = "DeparmentName"
cbPosition.DataSource = results.Tables(0) 'Filled two tables in one database call
cbDepartment.DataSource = results.Tables(1)
End Sub
I am wondering why you need a separate form when you could edit the data directly in the DGV. When you think of it, all the data you're trying to edit is already found in the DGV (or should exist in its datasource). You can even have combo boxes inside the DGV, with their own bound datatables. Here is an example that shows how it could be done.
In Edit_Load there is unnecessary repetition. You load the same dataset twice. You could reuse it or even load it at startup and keep it in cache if it's not changing during application runtime.
Plus, rather than fetch values from the DGV, it would better to fetch the selected datarow instead. For this you just need the record ID...
There is no need to access UI attributes, use the underlying datatable instead.
You shouldn't be using index numbers. Imagine the mess and potential for bugs if you want to insert columns or move columns. Also, the user probably can reorder columns in the DGV by drag & drop... thus your logic is ruined and the program will not behave like it should.
Anyway, to answer your issue: you've loaded a datatable, now all you have to do is bind it to the combo (which you did). You have used the DataSource and DisplayMember attributes. You could use SelectedValue to preselect a value in the list like this:
With cbPosition
.DisplayMember = "PositionName"
.ValueMember = "PositionName"
.SelectedValue = "The text value that comes from the DGV"
.DataSource = postable
End With
As long as the value from the DGV is present in the datatable this should work.
Again, I think you should simplify your UI. All the data could be edited in-place in the DGV.

combobox recalling previous datasource

Looking for some insight here...
On my form, I have three ComboBox controls. When the left most receives a selection, it calls a routine to enable and populate the 2nd, then the same happens for the 3rd when a selection is made in the 2nd.
Private Sub cboEquipment_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboEquipment.SelectedIndexChanged
Me.transData.isMobile = If(Me.cboEquipment.Text = MOBIEQIP, 1, 0)
If cboMembership.Enabled = False Then
Me.cboMembership.Enabled = True
End If
Call loadGroups()
End Sub
The method 'loadGroups'
Private Sub loadGroups()
Dim cn As New SqlConnection(My.Settings.MyConnectionString)
Dim cm As New SqlCommand("SELECT ... ORDER BY codeHumanName ASC", cn)
Dim ta As New SqlDataAdapter(cm)
Dim dt As New DataTable
Me.cboMembership.DataSource = Nothing
Me.cboMembership.Items.Clear()
Me.transData.membership = Nothing
cn.Open()
ta.Fill(dt)
With Me.cboMembership
.DataSource = dt
.DisplayMember = "codeHumanName"
.ValueMember = "codeID"
End With
cn.Close()
End Sub
This works fine an dandy, everything loads at should, and provides the appropriate .ValueMember results.
I should mention that when the Form first loads, boxes 2 and 3 are empty and disabled. After their initial load, I have to select an item from the list to get values (as expected).
The odd part is that once the 2nd or 3rd Combobox have been 'initialized', they seem to recall last settings. For example, if I call the Reset method, which sets the .DataSource property to Nothing, clear the list, and set the Text to Nothing; the next time I change the SelectedIndex on cboEquipment, the other boxes come back to life with SelectedItems and SelectedValues.
These values aren't wrong according to the new DataTable, but it is odd that they remember at all (they shouldn't have any reference, and behave as a fresh load).
Other points of interest; the populate methods are called during the SelectedIndexChanged event.
Any thoughts would be great!
UPDATE -
This behavior is tied in with the SelectedIndexChange Event bouncing around (raise! raise! raise!)
Removing and adding event handlers at strategic points has my code working as I want/expect it to.
Here is the article that put me on the right path...
On your second and third combo boxes try clearing the .Text/.SelectedText properties before you set the .DataTable
The combo box is probably just being too helpful and assuming that when you set the .DataTable a second time, you'd want the selected item to match your .Text property.
I ended up using AddHandler and RemoveHandler to prevent chain-firing events as the comboboxes were being populated.

How to reference controls located on different Tabs (VB.NET)

I have an application written in VB.NET that reads data from a file and displays the data on the screen.
Depending on the data in the file, the program has a TabControl with up to 3 tabs and each tab in turn has a DataGridView for displaying data. For example I have a TabControl that has a tab called "Saturday" and a tab called "Sunday".
The problem I am having is that when I read data from a file, the program displays all the data on the Saturday's tab grid because I am not sure how to reference the Grid on the Sunday tab.
To add the DataGridView I am using the following code:
Grid = New DataGridView
Grid.Dock = DockStyle.Fill
Grid.Name = "Grid" & TabControl.SelectedIndex
Grid.Tag = "Grid" & TabControl.SelectedIndex
And this is how I am reading the data in:
If reader.GetAttribute("controltype") = "Tab" Then
SelectedTab = reader.Name
End If
If reader.Name = "cell" Then
y = y + 1
Grid.Rows(i).Cells(y).Style.BackColor = Color.FromName(reader.ReadElementString("cell"))
End If
What I almost want to do is something like (pseudocode):
SelectedTab.Grid.Rows(i).Cells(y).Style.BackColor = Color.FromName(reader.ReadElementString("cell"))
However when I use the above code it complains:
'Grid' is not a member of 'String'
I hope you understand the issue. Let me know if you need clarification
Your code is a little unclear. However, it appears to me that the following line:
If reader.GetAttribute("controltype") = "Tab" Then
SelectedTab = reader.Name
End If
is creating at least one problem. It looks like you are attempting to refer to a Tabpage control by the string representation of its name, but unless I missed something, what that line is actually doing is trying to make a tabpage control type("SelectedTab") refer to a string type. If that is the case, then you will want to try this instead:
If reader.GetAttribute("controltype") = "Tab" Then
TabControl1.SelectedTab = TabControl1.TabPages(reader.name)
End If
It is a little hard to tell from the code you have posted, but that might get you headed down the right path.
++++++++++++
UPDATE: It appears from your code that you are naming each DGV control by appending the index of the tab on which it is located to the string "grid." I am going to assume that you are using a class member variable named "SelectedTab" to represent the current tab selected in the control. I will assume that at the top of your class you have done something like this:
'Form-or-class scoped memebr variables:
Private SelectedTab As TabPage
Private SelectedGrid As DataGridView
You should be able to refer to the active grid control using something like this:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
' Set SelectedTab member variable to refer to the new selected tab page:
SelectedTab = TabControl1.SelectedTab
' Set the SelectedGrid to refer to the grid control hosted on the selected tab page:
SelectedGrid = TabControl1.SelectedTab.Controls("Grid" & TabControl1.SelectedIndex.ToString())
End Sub
From here, you should be able to use the member variable for SelectedGrid to refer to the grid present on which ever tab page is selected in your tab control.
It is challenging to address your concerns with only fragments of your code. If you have additional difficulties, please post more of your code, so we can better see what else is going on.
Hope that helps!
Okay, I would go about something like this. Maybe you can simply use a DataSet to load the XML data in one line (if they have been saved with DataSet.WriteXML before).
Dim ds As New DataSet
Dim p As TabPage
Dim gv As DataGridView
ds.ReadXml("F:\testdata.xml")
For i As Integer = TabControl1.TabPages.Count - 1 To 0 Step -1
TabControl1.TabPages.RemoveAt(i)
Next
For Each dt As DataTable In ds.Tables
p = New TabPage(dt.TableName)
gv = New DataGridView
' ... configure the gv here...
gv.AutoGenerateColumns = True
gv.Dock = DockStyle.Fill
' ...
gv.DataSource = dt
TabControl1.TabPages.Add(p)
p.Controls.Add(gv)
Next

should changing the parent of a listbox change the selected index?

You wouldn’t think so, but it does when the listbox is bound to a datasource (as far as I can see).
I’ve reduced the behaviour to the code below. The "if" line toggles between loading a list via data binding and loading a list “manually” (both use the same data table). In each case I set the selected index afterwards, and then change the parent form. With manual loading, the selected index is retained, with binding it is lost. I cannot see how this makes any sense – I don't see why changing the host form should alter any property of the list. Is this a bug?
Public Class Form1
Sub main() Handles Me.Load
Dim ListControl1 As ListBox = New ListBox
ListControl1.Parent = Me
Dim dt = New DataTable
dt.Columns.Add("intColourID")
dt.Columns.Add("strName")
dt.Rows.Add({1, "Red"})
dt.Rows.Add({2, "Green"})
dt.Rows.Add({3, "Blue"})
ListControl1.ValueMember = dt.Columns(0).ColumnName
ListControl1.DisplayMember = dt.Columns(1).ColumnName
If False Then
ListControl1.DataSource = dt
Else
For i = 0 To dt.Rows.Count - 1
ListControl1.Items.Add(dt.Rows(i)("strName").ToString)
Next
End If
ListControl1.SelectedIndex = 2
Dim z As Form = New Form
ListControl1.Parent = z
z.Show()
End Sub
End Class
The correct way of adding a control to a form is not to set its parent, but to add it to the Controls collection of the form. If I do it like this I do not get an exception (the three last lines commented out as you write in your comment).
Me.Controls.Add(ListControl1) ' Instead of ListControl1.Parent = Me

DataGridView losing initial state specified at design time

When I try to change the datasource of my DataGridView, I am loosing the order of the columns and their type(checkboxes,comboboxes) that i specified at design time.
It's like changing the datasource is generating again the datagridview, why ? and How can I change the datasource without losing these information ?
Please if you know give me help
Thanks in advance
On form load i do something like
Private Sub frmGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Path as string
Path="C:\......Myfile.xml"
Dim oData as dataset
oData = New DataSet
oData.ReadXml(Path)
oData.AcceptChanges()
DataGridView1.DataSource = oData
DataGridView1.DataMember = oData.Tables(0).TableName
end sub
Till now everything is fine the design mode is preserved.
Then I have in my interface I have a button to save the content of my Grid to an excel file (it's an xml, formatted for excel)
Then i want to import this, on a button action, so i do the following
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim MyDs As DataSet
MyDs = New DataSet
Dim InputFileStream As New System.IO.FileStream(Path, System.IO.FileMode.Open)
MyDs = ImportExcelXML(InputFileStream, True, True)
MyDs.ReadXml(Path)
MyDs.AcceptChanges()
DataGridView1.DataSource = MyDs
DataGridView1.DataMember = MyDs.Tables(0).TableName
end sub
Probabily you have set up GenerateColums property to "True"
That means the GridView will generate the columns(name and number of them) againts the data sorce.
If the data source (in you case data table) are different it will come up a different grid.
If the datasource are different you can design the layout of your gridView but after that you have to manually bind the data to the columns as you wish.You can do that into
RowDataBound event.
The datatable you are trying to assign to the DataGridView1.DataSource is structured different from the way you defined the DataGridView at design time. Put a break point in your code right before you reassign the new DataTable to the DataSource and see what is different in the structure. It is most likely that you either have more or less DataColumns in place, or the columns could be in a different order. They might even be named different. If at design time you set your DataGridViewColumn's DataProperty to a specific name, than then name needs to be exact.
You'll just have to check it at that breakpoint and see what the differences are.
I found a solution, your hints helped me to look on the right direction to find a solution !
What i was doing was on form load
MaGrille.DataSource = oData
MaGrille.DataMember = oData.Tables(0).TableName
Then in the button click I do :
MaGrille.DataSource = MyDs
MaGrille.DataMember = MyDs.Tables(0).TableName
The problem is that the grid is rebuild and i loose the formatting, column order etc..
After many tests, I understood that It wasn't working because the names of datatables are differents ! I don't understand why, but it was the error as it seems.
I had the following values
oData.Tables(0) = "DECLARATION"
MyDs.Tables(0) = "Sheet1"
So I noticed that if I rename MyDs.Tables(0) by "DECLARATION" instead of "Sheet1", and i click on the button, this time I don't loose formatting, neither orders ...
This inspired me to find the SOLUTION :
After many tries, I realized that if instead of doing on form load
MaGrille.DataSource = oData
MaGrille.DataMember = oData.Tables(0).TableName
and on button click :
MaGrille.DataSource = MyDs
MaGrille.DataMember = MyDs.Tables(0).TableName
I do :
on form load
MaGrille.DataSource = oData.Tables(0)
and on button click
MaGrille.DataSource = MyDs.Tables(0)
All works fine even if the oData.Tables(0).TableName is different from MyDs.Tables(0).TableName !!
I found the solution Now, but still can't understand the WHY If anyone get an explication, please let me know.
Thanks to all again