vb.net. How do I bind dataset to DataRepeater? - vb.net

I am looking for a vb.net example of how to bind a dataset/datatable to data repeater and have the data elements bound to the columns of the dataset/datatable?
Thanks

At first I thought you wanted a web repeater, but from your comments I realized you meant Microsoft.VisualBasic.PowerPacks.DataRepeater.
I need some more info from you to give the most helpful sample code (see below).
The basic steps of using a DataRepeater are:
1) Install the Visual Basic Power Packs 3 Link
2) Open a VB.net Winforms project and drag a DataRepeater to your form
3) Add a new Dataset to your project via Add->New Item menu
4) In the design window, set up columns as desired
5) Open the Data Sources window from Data->ShowDataSources menu
6) With your form in design mode, go to the Dataset in the Data Sources window and use the dropdown box next to the table name to select "Details"
7) Drag the table to top section of the DataRepeater control (on your form). The table fields should now be listed on your DataRepeater. You can move them around.
8) At runtime, you can load the Datset and the DataRepeater will automatically reflect the data changes. No .Databind is required
ex.
me.DataSet1.Tables(0).Columns.Add(New String() {"John", "Doe", "Accountant"}
or
myDataAdapter.Fill(me.DataSet1.Tables(0))
Do you get tripped up on any of those steps?
Edit:
From what I have seen, it looks like DataRepeater is meant to be used in situations were you add/map the datatable to the DataRepeater at design-time. Then all you have to do is fill the datatable at run-time and the DataReader shows the data automatically.
If you really want to add the table/controls to the DataRepeater at run time, here's an example I coded for you. It assumes a form named Form3 with a DataRepeater named DataRepeater1 and a button named Button1...
Public Class Form3
''Set up demo DataSet/DataTable
Const FRUIT_COL As String = "Fruit"
Const COLOR_COL As String = "Color"
MyDataSet = New DataSet
MyDataSet.Tables.Add("MyTable")
With MyDataSet.Tables(0)
.Columns.Add(FRUIT_COL, GetType(System.String))
.Columns.Add(COLOR_COL, GetType(System.String))
End With
''Populate the DataTable with sample data. You would be loading from SQL
With MyDataSet.Tables(0)
.Rows.Add(New String() {"Apple", "Red"})
.Rows.Add(New String() {"Orange", "Orange"})
.Rows.Add(New String() {"Banana", "Yellow"})
End With
''These objects would normally be created automatically if you added DataTable to DataRepeater at design-time
FruitLabel = New Label
FruitTextBox = New TextBox
ColorLabel = New Label
ColorTextBox = New TextBox
With FruitLabel
.AutoSize = True
.Location = New Point(10, 20)
.Name = "FruitLabel"
.Text = FRUIT_COL
End With
With ColorLabel
.AutoSize = True
.Location = New Point(10, 60)
.Name = "FruitLabel"
.Text = FRUIT_COL
End With
With FruitTextBox
.Location = New Point(50, 20)
.Size = New Size(60, 15)
.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.MyDataSet.Tables(0), FRUIT_COL, True))
End With
With ColorTextBox
.Size = New Size(60, 15)
.Location = New Point(50, 60)
.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.MyDataSet.Tables(0), COLOR_COL, True))
End With
''Add the controls that will be displayed for each row in DataTable
With DataRepeater1
.ItemTemplate.Controls.Add(FruitLabel)
.ItemTemplate.Controls.Add(FruitTextBox)
.ItemTemplate.Controls.Add(ColorLabel)
.ItemTemplate.Controls.Add(ColorTextBox)
End With
''Run-time population of DataRepeater from your DataTable
DataRepeater1.DataSource = MyDataSet
DataRepeater1.DataMember = MyDataSet.Tables(0).TableName
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Example of how you can add additional rows with form elements
With MyDataSet.Tables(0)
.Rows.Add(New String() {"Grapes", "Green"})
End With
End Sub
End Class
Now that you have seen the code, I hope you don't use it :)
I suggest you either set up your DataSet structure at design-time or use a different control to display your data.
Here's a link that has lots of information about the typical way to use DataRepeater:
Link
Final Edit
The user's last bug was a case-sensitivity issue. The string "Text" in the following line of code must be capitalized to match the control's property name. I recommend creating a const for "Test" to avoid this typo.
[ControlName].DataBindings.Add(New System.Windows.Forms.Binding("Text", [DataTable], [Column Name], True))

Dim data As DataSet
DataRepeater1.DataSource = data
DataRepeater1.DataBind()

Related

How to access cells from programmatically created datagridview in 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

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

Slow DataGridView Drawing\Rendering

I'm using a DataGridView to load data from a DataTable. This DataGridView is located on a tab (Forms.TabPage). When clicking this tab the datagrid takes a second or two to draw from the top down, regardless of wheather data is being loaded or not.
Is there anything I can do to speed up the Drawing\Rendering when clicking the Tab?
I Don't think the actual population of the DGV is causing this, as it's filled during form load so by the time the tabs click it would have loaded the few rows (20 - 30) it displays.
Using cn As New SqlConnection(connectionString)
Using cmd As SqlCommand = cn.CreateCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = _
" SELECT [finish_time], [file_name], [transfer_status]" & _
" FROM dbo.[transfer_log]"
cmd.Notification = Nothing
cn.Open()
Dim columnSpec = New DataColumn()
With columnSpec
.DataType = GetType(System.String)
.ColumnName = "ClmFinishTime"
End With
Datatable1.Columns.Add(columnSpec)
Dim columnSpec2 = New DataColumn()
With columnSpec2
.DataType = GetType(System.String)
.ColumnName = "ClmFilename"
End With
Datatable1.Columns.Add(columnSpec2)
Dim columnSpec3 = New DataColumn()
With columnSpec3
.DataType = GetType(System.Byte())
.ColumnName = "ClmStatus"
End With
Datatable1.Columns.Add(columnSpec3)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim row As DataRow = Datatable1.NewRow
row("ClmFinishTime") = dr.Item("finish_time")
row("ClmFilename") = dr.Item("file_name")
Select Case dr.Item("transfer_status")
Case 0
row("ClmStatus") = ConvertToByte(My.Resources.accept)
Case 1
row("ClmStatus") = ConvertToByte(My.Resources.remove)
End Select
Datatable1.Rows.Add(row)
End While
End Using
End Using
DataGridView2.AutoGenerateColumns = False
DataGridView2.DataSource = Datatable1
I fixed this by double buffering the control:
Public Shared Sub SetDoubleBuffered(ByVal control As Control)
GetType(Control).InvokeMember("DoubleBuffered", BindingFlags.SetProperty Or BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, control, New Object() {True})
End Sub
My two cents on this. I had a DGV that was extremely slow, even with only 100 records. Running the query wasn't the issue -- it returned results in milliseconds.
I tried the various 'doublebuffer' techniques, to no avail.
With my DGV on a TabControl, I was thinking there was possibly an issue with TabControls + DGVs.
To troubleshoot this, I created a new form, added a DGV, and had it populate the DGV on the form load event. I was quite happy to see the data loaded instantly.
I then started going through each property I had set on my original DGV, changing only one at a time, then opening the form. The DGV loaded instantly, until I set the RowHeadersWidthSizeMode. The default setting for this is 'EnableResizing', whereas my original, slow DGV had been changed to 'AutoSizeToAllHeaders'.
vs.
Sure enough, setting this back to the default of 'EnableResizing' resolved my slow DGV issue. I'm able to reproduce this side-by-side. Leave the DGV # 'EnableResizing', DGV loads instantly. Change it to 'AutoSizeToAllHeaders' and it takes 1-2 seconds before the DGV loads.
Just thought I'd share my experience with this.
Alternatively to #madlan simply set the DoubleBuffered property in the constructor by inheriting the control.
public class DoubleBufferedDataGridView : DataGridView
{
public DoubleBufferedDataGridView() : base()
{
this.DoubleBuffered = true;
}
}
I had a similar problem due to placing the DataGridView object into a TableLayoutPanel. The default behavior in Visual Studio of a TableLayoutPanel has the following property:
Focus -> CausesValidation = True
Due to this, it was taking up to 10 minutes to populate the DataGridView from a large DataTable.
In the Forms Designer, I set this value to
Focus -> CausesValidation = False
My DataGridView now works properly, it redraws in a second or less, and its data source is linked to a DataTable containing 2,000 rows and 100 columns, some cells holding text of up to 32,767 characters. Its response to the user editing cells etc. has no apparent delay.