How to access cells from programmatically created datagridview in VB.net? - vb.net

When creating a datagridview in VB.net I cannot get at the cells from anywhere except the Sub where it was made.
I tried placing the code in Form_Load and tried make the Sub Public.
I use Controls.Find, which finds the datagridview, but I cannot access any rows or cells. I can create textbox and label controls and access their text content from anywhere, but not so with the datagridview. This is odd to me.
Using and learning Visual Basic in Visual Studio 2017, for use in my own home business utility.
Dim dgv As New DataGridView
dgv.Location = New Point(2, 200)
dgv.Size = New Size(300, 50)
dgv.Name = "NewDGV"
Dim ColumnTitles() As String = {"ProdId", "Price"}
Dim ColumnWidths() As Integer = {50, 50)
For i = 0 To UBound(ColumnTitles)
Dim col As New DataGridViewTextBoxColumn
col.DataPropertyName = ColumnTitles(i)
col.HeaderText = ColumnTitles(i)
col.Name = ColumnTitles(i)
col.Width = ColumnWidths(i)
dgv.Columns.Add(col)
Next
Controls.Add(dgv)
‘the following sees the datagridview just fine
‘within the same sub
Dim x = dgv.Rows(0).Cells(0).Value
This is how I am creating this control. Perhaps I am Adding to Controls in the wrong way? I am open to better ways to do this.

Dim dgv As DataGridView = CType(Controls("NewDGV"), DataGridView)
dgv.Rows(0).Cells(0).Value = "I found you!"
What this does is find the first Control in the Controls collection, coerces it into a DataGridView type, and assigns it to the variable dgv. You can than manipulate dgv. In this case I put some text in the first cell on the first row.

You could ask the control collection for the instance of your datagridview
Dim MyDgv As DataGridView = Controls.Cast(Of DataGridView).First(Function(dgv) dgv.Name = "NewDGV")
Then work with "MyDGV" properties, methods, and/or events

Related

Accessing Textbox programmatically created

I need to read a datagrid numbers of items, and programmatically add tabs to one tabControl. No problem on reading the datagrid, no problem in creating the model in the tabcontrol. So, I read the number of items, create the tabs accordingly, with all textboxes already with the correct values and so on.
At this point, the user will update some information on the tabs created, and need to click a Update button. At this point, I need to read all tabs, one by one, accessing all textboxes created, and send this to my database.
The only thing I got no result till now is “How to access these programmatically created Textboxes?
This is how I create the textboxes inside the TabControl
Dim TXT As New TextBox
TXT = New TextBox
TXT.Location = New System.Drawing.Point(213, 25)
TXT.Width = 303
TXT.TextAlign = HorizontalAlignment.Center
TXT.Name = "TXT_02_" & tab_counter
TXT.Text = MAT_DTCP(1) 'ABERTURA
TXT.BackColor = ColorTranslator.FromOle(RGB(128, 255, 255))
FORM_01.TBC_DTCP.SelectedTab.Controls.Add(TXT)
You could use LINQ:
Dim allTextBoxes = From tab In FORM_01.TBC_DTCP.TabPages.Cast(Of TabPage)()
From txt In tab.Controls.OfType(Of TextBox)()
Where txt.Name.StartsWith("TXT_02_")
Select txt
For Each txt As TextBox In allTextBoxes
' ... '
Next

Access a dynamically created textbox text from another sub. And I also want to be user-configurable and access the user-configured text

Textbox.text I want to access. And I want it user-configurable before I want to access the altered text.
Dim qbox As New TextBox
qbox.Size = New Size(20, 20)
qbox.Location = New Point(90, 10)
qbox.Parent = addtocart
qbox.Name = "quarts"
qbox.Text = "ss"**
how I dynamically add it inside a series of other dynamic controls:
tile.Controls.Add(addtocart)
flpp.Controls.Add(tile)
tile.Controls.Add(plabel)
tile.Controls.Add(nlabel)
addtocart.Controls.Add(qbox)
How I tried to access it:
qb.Text = CType(Me.Controls("flpp").Controls("tile").Controls("addtocart").Controls("qbox"), TextBox).Text
I generated to textbox at runtime. Of course it's dynamic. I'm new to VB and I'm just experimenting a school project. I wanted the textbox text to be configurable and then access that configured value. I've been brain-cracking for days about this. when I run the thing, I "getObject reference not set to an instance of an object." under NullReferenceException was unhandled" something like this. I don't get it.
WinForms? If yes, and you want to find that control "by name", then use the Controls.Find() function:
Dim ctlName As String = "quarts"
Dim matches() As Control = Me.Controls.Find(ctlName, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim tb As TextBox = DirectCast(matches(0), TextBox)
' ... use "tb" somehow ...
Dim value As String = tb.Text
MessageBox.Show(value)
End If

DataGridView bound to DataTable is not showing

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.

Add tooltip control dynamically

I have a child form that is completely created in code.
I would like to add tool tips to the textbox controls on the form. I know how to set up the tool tips on the fly but can't find a way to add the tooltip control to the form on the fly. All the hits I find on google refer to dragging the control from the designers toolbox.
I would need to do something like:
' Add tool tip control
Dim toolTip1 As New ToolTip()
toolTip1.ShowAlways = True
frm.Controls.Add(toolTip1)
This does not work
I tried adding a sub to handle the from.load event(with a handler that poitn to the sub) at design time but can not get passed the error "Tooltip1 is not declared" when adding the tooltip to the iundividual dynamic controls.
If I call this dynamic form from a parent form and add the tooltip control to the parent form I can use it for the child form. But how would I do this if I was creating the form from a routine that does not live on a parent form?
thanks
Dim frm As New Form
' Add tool tip control
''Dim toolTip1 As New ToolTip()
''toolTip1.ShowAlways = True
'Draw the Form object
'close the dynamic frm if existing already
If frm IsNot Nothing Then
frm.Close()
End If
frm = New Form()
frm.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F)
frm.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
frm.Name = "frm_test"
'dimension is irrelevant at the moment
frm.ClientSize = New System.Drawing.Size(10, 10)
'the parent will be the current form
'frm.MdiParent = this;
'splash screen mode form, why not...
frm.ControlBox = True
frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
frm.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
frm.BackColor = System.Drawing.Color.LightGray
For Each item As MYFILE.Class in the Collection
Dim aTextBox As New TextBox()
aTextBox.Font = New System.Drawing.Font(sFont, Single.Parse(sSizeFont), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CByte(0))
aTextBox.BackColor = System.Drawing.Color.Yellow
aTextBox.Location = New System.Drawing.Point(iNewColumnPosition + 5 + intMaxWidthLabel, intVertPos)
aTextBox.Size = New System.Drawing.Size(intWidthTextBox + 10, intGapHeight)
'store the biggest width, so that the textboxes can be vertically aligned
If intWidthTextBox > intMaxWidthText Then
intMaxWidthText = intWidthTextBox
End If
'giving a name to all your object will be the only way
'to retrieve them and use them
'for the purpose of this sample, the name can be the
'same for all textboxes.
aTextBox.Name = item.ParameterName
'giving the maximun size in caracters for the textbox.
aTextBox.MaxLength = Integer.Parse(item.ParameterLength)
toolTip1.SetToolTip(aTextBox, "TIP" & intIndex.ToString)
'tab have to be ordered
aTextBox.TabIndex = intIndex
intIndex += 1
'Vertical position is to be manage according the
'tallest object in the form, in this case the
'textbox it self
intVertPos += intGapHeight
'adding the textbox to the form
frm.SuspendLayout()
aTextBox.SuspendLayout()
frm.Controls.Add(aTextBox)
Next
I left a lot of code out but this should give you an idea as to what I am doing
In vb it is
Dim tooltip As New ToolTip(components)
tooltip.SetToolTip(textBox1, "This is a textbox tooltip")
Sorry this is not in VB.NET but I am pretty sure you can easily convert this. The first line is to set ToolTip control to your form components. The second is how you set a tooltip to a control and give it the related text.
ToolTip tooltip = new ToolTip(components);
tooltip.SetToolTip(textBox1, "This is a textbox tooltip");

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