I'm reading an XML file and storing the results into a DataSet. This dataset contains 10 DataTables. I would like to join all DataTables into one datatable and use this table to set as a datasource for a datagridview so I can later export the gridview into csv or excel. Currently I'm displaying each datatable in a separate gridview. I have tried datatable.merge() but that didn't work.
Any suggestions on how I can display this 10 datatables in a single datagridview?
Thanks
Imports System.Xml
Public Class Form1
Public tbl0 As New DataTable
Public tbl1 As New DataTable
Public tbl2 As New DataTable
Public tbl3 As New DataTable
Public tbl4 As New DataTable
Public tbl5 As New DataTable
Public tbl6 As New DataTable
Public tbl7 As New DataTable
Public tbl8 As New DataTable
Public tbl9 As New DataTable
Public result As New DataTable
Private Sub btnreadxml_Click(sender As Object, e As EventArgs) Handles btnreadxml.Click
Try
Dim filePath As String
filePath = "C:/Win/XMLReader/822396000069521.xml"
AuthorsDataSet.ReadXml(filePath)
tbl0 = AuthorsDataSet.Tables(0)
tbl1 = AuthorsDataSet.Tables(1)
tbl2 = AuthorsDataSet.Tables(2)
tbl3 = AuthorsDataSet.Tables(3)
tbl4 = AuthorsDataSet.Tables(4)
tbl5 = AuthorsDataSet.Tables(5)
tbl6 = AuthorsDataSet.Tables(6)
tbl7 = AuthorsDataSet.Tables(7)
tbl8 = AuthorsDataSet.Tables(8)
tbl9 = AuthorsDataSet.Tables(9)
DataGridView1.DataSource = tbl1
DataGridView2.DataSource = tbl2
DataGridView3.DataSource = tbl3
DataGridView4.DataSource = tbl4
DataGridView5.DataSource = tbl5
DataGridView6.DataSource = tbl6
DataGridView7.DataSource = tbl7
DataGridView8.DataSource = tbl8
DataGridView9.DataSource = tbl9
Catch ex As Exception
End Try
End Sub
There isn't one simple answer to this question but there are things you can do to make this more trivial. The following code are based on the following data schema.
Our goal is to solve this task using LINQ.
The first thing we should do is to create custom classes reflecting the data schema.
Public Class Author
Public Property pk_author As Integer
Public Property firstname As String
Public Property lastname As String
End Class
Public Class Book
Public Property pk_book As Integer
Public Property fk_author As Integer
Public Property title As String
End Class
Public Class Review
Public Property pk_review As Integer
Public Property fk_book As Integer
Public Property [text] As String
End Class
Next we'll need to create two extension/helper method. (You'll find the full source code at the bottom of this post.)
ToDataTable
This function will turn a List(Of T) into a DataTable based on the properties defined in T.
<Extension()>
Public Function ToDataTable(Of T)(source As List(Of T)) As DataTable
ToList
This function will turn a DataTable into a List(Of T) based on the properties defined in T and columns contained by the source table.
<Extension()>
Public Function ToList(Of T As {Class, New})(source As DataTable) As List(Of T)
Usage
Read the XML file into a DataTable
Dim [set] As DataSet = ReadXmlIntoDataSet()
"Convert" the tables into lists.
Dim authors As List(Of Author) = [set].Tables("authors").ToList(Of Author)()
Dim books As List(Of Book) = [set].Tables("books").ToList(Of Book)()
Dim reviews As List(Of Review) = [set].Tables("reviews").ToList(Of Review)()
Use LINQ to join the lists and then "convert" the result back to a DataTable.
Dim results As DataTable = (
From a In authors
From b In books.Where(Function(item) ((Not a Is Nothing) AndAlso item.fk_author = a.pk_author)).DefaultIfEmpty()
From r In reviews.Where(Function(item) ((Not b Is Nothing) AndAlso item.fk_book = b.pk_book)).DefaultIfEmpty()
Select New With {
.pk_author = If((Not a Is Nothing), New Integer?(a.pk_author), Nothing),
.pk_book = If((Not b Is Nothing), New Integer?(b.pk_book), Nothing),
.pk_review = If((Not r Is Nothing), New Integer?(r.pk_review), Nothing),
.firstname = If((Not a Is Nothing), a.firstname, Nothing),
.lastname = If((Not a Is Nothing), a.lastname, Nothing),
.title = If((Not b Is Nothing), b.title, Nothing),
.[text] = If((Not r Is Nothing), r.[text], Nothing)
}
).ToList().ToDataTable()
Source code
References
Imports System.Runtime.CompilerServices
Imports System.ComponentModel
Imports System.Reflection
Imports <your namespace goes here>.Extensions
Author
Public Class Author
Public Property pk_author As Integer
Public Property firstname As String
Public Property lastname As String
End Class
Book
Public Class Book
Public Property pk_book As Integer
Public Property fk_author As Integer
Public Property title As String
End Class
Review
Public Class Review
Public Property pk_review As Integer
Public Property fk_book As Integer
Public Property [text] As String
End Class
Extensions
<Extension()>
Public Module Extensions
<Extension()>
Public Function ToDataTable(Of T)(source As List(Of T)) As DataTable
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
Dim table As New DataTable()
Dim descriptor As PropertyDescriptor = Nothing
Dim column As DataColumn = Nothing
Dim values As Object() = Nothing
Dim length As Integer = Nothing
Dim index As Integer = Nothing
Dim item As T = Nothing
Dim type As Type = Nothing
table.BeginInit()
For Each descriptor In properties
type = Nullable.GetUnderlyingType(descriptor.PropertyType)
column = New DataColumn()
column.ColumnName = descriptor.Name
column.Caption = descriptor.DisplayName
column.DataType = If((type Is Nothing), descriptor.PropertyType, type)
column.ReadOnly = descriptor.IsReadOnly
table.Columns.Add(column)
Next
table.BeginLoadData()
length = (properties.Count - 1)
values = New Object(length) {}
For Each item In source
For index = 0 To length
values(index) = properties(index).GetValue(item)
Next
table.Rows.Add(values)
Next
table.EndLoadData()
table.EndInit()
Return table
End Function
<Extension()>
Public Function ToList(Of T As {Class, New})(source As DataTable) As List(Of T)
If (source Is Nothing) Then
Throw New ArgumentNullException("source")
End If
Dim list As New List(Of T)
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
Dim descriptor As PropertyDescriptor = Nothing
Dim index As Integer = Nothing
Dim row As DataRow = Nothing
Dim item As T = Nothing
For index = (properties.Count - 1) To 0 Step -1
If (Not source.Columns.Contains(properties(index).Name)) Then
properties.RemoveAt(index)
End If
Next
For Each row In source.Rows
item = New T()
For Each descriptor In properties
descriptor.SetValue(item, row.Item(descriptor.Name))
Next
list.Add(item)
Next
Return list
End Function
End Module
Sample application
Public Class Form1
Public Sub New()
Me.InitializeControls()
Try
Dim [set] As DataSet = Form1.ReadXmlIntoDataSet()
Dim authors As List(Of Author) = [set].Tables("authors").ToList(Of Author)()
Dim books As List(Of Book) = [set].Tables("books").ToList(Of Book)()
Dim reviews As List(Of Review) = [set].Tables("reviews").ToList(Of Review)()
Dim results As DataTable = (
From a In authors
From b In books.Where(Function(item) ((Not a Is Nothing) AndAlso item.fk_author = a.pk_author)).DefaultIfEmpty()
From r In reviews.Where(Function(item) ((Not b Is Nothing) AndAlso item.fk_book = b.pk_book)).DefaultIfEmpty()
Select New With {
.pk_author = If((Not a Is Nothing), New Integer?(a.pk_author), Nothing),
.pk_book = If((Not b Is Nothing), New Integer?(b.pk_book), Nothing),
.pk_review = If((Not r Is Nothing), New Integer?(r.pk_review), Nothing),
.firstname = If((Not a Is Nothing), a.firstname, Nothing),
.lastname = If((Not a Is Nothing), a.lastname, Nothing),
.title = If((Not b Is Nothing), b.title, Nothing),
.[text] = If((Not r Is Nothing), r.[text], Nothing)
}
).ToList().ToDataTable()
Me.resultsGrid.DataSource = results
Me.authorsGrid.DataSource = authors
Me.booksGrid.DataSource = books
Me.reviewsGrid.DataSource = reviews
Catch ex As Exception
MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub InitializeControls()
Me.Label1 = New System.Windows.Forms.Label() With {.AutoSize = True, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 213), .Name = "Label1", .Size = New System.Drawing.Size(60, 18), .TabIndex = 0, .Text = "Reviews"}
Me.Label2 = New System.Windows.Forms.Label() With {.AutoSize = True, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 142), .Name = "Label2", .Size = New System.Drawing.Size(45, 18), .TabIndex = 4, .Text = "Books"}
Me.Label3 = New System.Windows.Forms.Label() With {.AutoSize = True, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 71), .Name = "Label3", .Size = New System.Drawing.Size(57, 18), .TabIndex = 7, .Text = "Authors"}
Me.Label4 = New System.Windows.Forms.Label() With {.AutoSize = True, .Dock = System.Windows.Forms.DockStyle.Top, .Font = New System.Drawing.Font("Calibri", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)), .Location = New System.Drawing.Point(0, 0), .Name = "Label4", .Size = New System.Drawing.Size(51, 18), .TabIndex = 10, .Text = "Result:"}
Me.Splitter1 = New System.Windows.Forms.Splitter() With {.BackColor = System.Drawing.Color.Gray, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 203), .Name = "Splitter1", .Size = New System.Drawing.Size(613, 10), .TabIndex = 2, .TabStop = False}
Me.Splitter2 = New System.Windows.Forms.Splitter() With {.BackColor = System.Drawing.Color.Gray, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 132), .Name = "Splitter2", .Size = New System.Drawing.Size(613, 10), .TabIndex = 5, .TabStop = False}
Me.Splitter3 = New System.Windows.Forms.Splitter() With {.BackColor = System.Drawing.Color.Gray, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 61), .Name = "Splitter3", .Size = New System.Drawing.Size(613, 10), .TabIndex = 8, .TabStop = False}
Me.resultsGrid = New System.Windows.Forms.DataGridView() With {.AllowUserToAddRows = False, .AllowUserToDeleteRows = False, .BackgroundColor = System.Drawing.Color.White, .ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 18), .Name = "resultsGrid", .ReadOnly = True, .Size = New System.Drawing.Size(613, 280), .TabIndex = 9}
Me.authorsGrid = New System.Windows.Forms.DataGridView() With {.AllowUserToAddRows = False, .AllowUserToDeleteRows = False, .BackgroundColor = System.Drawing.Color.White, .ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 89), .Name = "authorsGrid", .ReadOnly = True, .Size = New System.Drawing.Size(613, 115), .TabIndex = 6}
Me.booksGrid = New System.Windows.Forms.DataGridView() With {.AllowUserToAddRows = False, .AllowUserToDeleteRows = False, .BackgroundColor = System.Drawing.Color.White, .ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize, .Dock = System.Windows.Forms.DockStyle.Top, .Location = New System.Drawing.Point(0, 160), .Name = "booksGrid", .ReadOnly = True, .Size = New System.Drawing.Size(613, 200), .TabIndex = 3}
Me.reviewsGrid = New System.Windows.Forms.DataGridView() With {.AllowUserToAddRows = False, .AllowUserToDeleteRows = False, .BackgroundColor = System.Drawing.Color.White, .ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize, .Dock = System.Windows.Forms.DockStyle.Fill, .Location = New System.Drawing.Point(0, 231), .Name = "reviewsGrid", .ReadOnly = True, .Size = New System.Drawing.Size(613, 415), .TabIndex = 1}
Me.SuspendLayout()
Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 18.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(613, 900)
Me.Controls.AddRange({Me.reviewsGrid, Me.Label1, Me.Splitter1, Me.booksGrid, Me.Label2, Me.Splitter2, Me.authorsGrid, Me.Label3, Me.Splitter3, Me.resultsGrid, Me.Label4})
Me.Font = New System.Drawing.Font("Calibri", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Private Shared Function ReadXmlIntoDataSet() As DataSet
Dim [set] As New DataSet()
Dim authors As DataTable = [set].Tables.Add("authors")
With authors
.Columns.Add("pk_author", GetType(Integer))
.Columns.Add("firstname", GetType(String))
.Columns.Add("lastname", GetType(String))
.BeginLoadData()
.Rows.Add(1, "William", "Shakespeare")
.Rows.Add(2, "Henrik", "Ibsen")
.Rows.Add(3, "Ernest", "Hemingway")
.EndLoadData()
.AcceptChanges()
End With
Dim books As DataTable = [set].Tables.Add("books")
With books
.Columns.Add("pk_book", GetType(Integer))
.Columns.Add("fk_author", GetType(Integer))
.Columns.Add("title", GetType(String))
.BeginLoadData()
.Rows.Add(1, 1, "Timon of Athens")
.Rows.Add(2, 1, "Titus Othello")
.Rows.Add(3, 1, "The Comedy of Errors")
.Rows.Add(4, 2, "Peer Gynt")
.Rows.Add(5, 2, "A Doll's House")
.Rows.Add(6, 2, "Emperor and Galilean")
.EndLoadData()
.AcceptChanges()
End With
Dim reviews As DataTable = [set].Tables.Add("reviews")
With reviews
.Columns.Add("pk_review", GetType(Integer))
.Columns.Add("fk_book", GetType(Integer))
.Columns.Add("text", GetType(String))
.BeginLoadData()
.Rows.Add(1, 1, "The book 'Timon of Athens' blabla ...")
.Rows.Add(2, 2, "The book 'Titus Othello' blabla ...")
.Rows.Add(3, 4, "The book 'Peer Gynt' blabla 1...")
.Rows.Add(4, 4, "The book 'Peer Gynt' blabla 2...")
.Rows.Add(5, 4, "The book 'Peer Gynt' blabla 3...")
.Rows.Add(6, 5, "The book 'A Doll's House' blabla ...")
.EndLoadData()
.AcceptChanges()
End With
[set].Relations.Add(New DataRelation("books_author", authors.Columns("pk_author"), books.Columns("fk_author")))
[set].Relations.Add(New DataRelation("reviews_books", books.Columns("pk_book"), reviews.Columns("fk_book")))
Return [set]
End Function
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents Splitter1 As System.Windows.Forms.Splitter
Friend WithEvents Splitter2 As System.Windows.Forms.Splitter
Friend WithEvents Splitter3 As System.Windows.Forms.Splitter
Friend WithEvents resultsGrid As System.Windows.Forms.DataGridView
Friend WithEvents authorsGrid As System.Windows.Forms.DataGridView
Friend WithEvents booksGrid As System.Windows.Forms.DataGridView
Friend WithEvents reviewsGrid As System.Windows.Forms.DataGridView
End Class
Related
I am trying to figure out the functions for an application that you order donuts and coffee through. There is no box to input quantities. The type of doughnuts are selected using radio buttons grouped in combo boxes as is the type of coffee. The user ordering does not input any information. That application calculates according to the selected radio buttons. There is also a 3% sales tax.
The donuts are as follows:
Glazed are $0.65, Sugar $0.65, Chocolate are $0.85, and Filled are $1.00.
The coffee costs:
Regular is $1.00 and cappuccino is $2.50.
How do I write a function for each one? I would think I would just write one function that calculates the donut, coffee and sales tax. I am not sure what I am supposed to include if there is only one possible choice for each case. I thought that I could just write a bunch of constants since nothing changed and do an If statement but the assignment is asking for functions.
This is what I have so far for the doughnuts.
Private Function GetDonutPrice(ByVal strDonut As String) As Double
Dim dblDonutPrice As Double
'Calculates and returns the price of donuts
If strDonut = "G" Or strDonut = "S" Then
dblDonutPrice = 0.65
ElseIf strDonut = "C" Then
dblDonutPrice = 0.85
Else
strDonut = "F"
dblDonutPrice = 1.0
End If
Return dblDonutPrice
End Function
And then for the btnCalc_Click I coded this:
Private Sub btnCalc_Click(sender As Object, e As EventArgs)
'Displays donut and cappucino subtotal, taxes and price
Dim strDonutPrice As String
Dim dblDonutPrice As Double
If radGlazed.Checked Then
strDonutPrice = "G"
ElseIf radSugar.Checked Then
strDonutPrice = "S"
ElseIf radChoc.Checked Then
strDonutPrice = "C"
ElseIf radFilled.Checked strDonutPrice = "F"
End If
' get the donut price '
dblDonutPrice = GetDonutPrice(strDonutPrice)
End Sub
And I get an error in dblDonutPrice = GetDonutPrice(strDonutPrice)
It sounds like you need a function that receives the type and quantity of doughnuts and does the math and returns the cost. And the same for the coffee. So you will have three functions total. The coffee, the doughnuts, and the main one that take the input of what is order and how many, calls the other functions, adds it up, and then does the sales tax
Something like this maybe.
Private Sub cmdAddItUp_Click(sender As System.Object, e As System.EventArgs) Handles cmdAddItUp.Click
Dim iQuantity1 as integer
Dim dDoughnutCost as double
'Get the data to send to doughnuts
iQuantity1 = val(TextBox1.Text)
iQuantity2 = val(TextBox2.Text)
etc.
'Get the doughnuts cost
dDoughnutCost = Doughtnuts(iQuantity1, iQuantity2, iQuantity3)
'Do the same for the coffee
dCoffeeCost = Coffees(iQuantity1, iQuantity2, iQuantity3)
'Add it up
dSubTotal = dDoughnutCost + dCoffeeCost
'Calculate tax
dTotal = Tax(dSubTotal)
'Now you have the total, do something with it. Display it maybe!
End Sub
Private Function Doughtnuts(iQuantity1 As Integer, iQuantity2 As Integer, iQuantity3 As Integer) As Double
'Do the math
End Function
Private Function Coffees(iQuantity1 As Integer, iQuantity2 As Integer, iQuantity3 As Integer) As Double
'Do the math
End Function
Private Function Tax(dSubtotal As Double) As Double
'Calculate tax
End Function
Hope that helps get you started. Good luck with your schooling.
I made some assumptions on your UI. Rather than placing the items as radio buttons in a ComboBox, I placed all of the doughnuts and coffees into a respective GroupBox. The concepts of this answer will still apply, however you'll just have to be mindful that this is not directly drop-in and go.
Here's the way I laid out the UI:
I have placed the RadioButtons for the items inside a FlowLayoutPanel inside of a GroupBox. I also placed labels into a TableLayoutPanel to provide the total amounts.
The most important part is how I named the RadioButton controls for the items being listed. In the code behind file I used the names of the RadioButton controls to check which Item was being modified. I could have populated the RadioButton controls at run time to ensure that everything lined up, but that was more work and it's not difficult to do if you use GetType(MyEnum).GetNames() in the Me.Load event of the form to create new RadioButtons with the correct name, text, and adding the proper event handlers to the radio buttons.
If you'd like to see how this works, add a new form to your Project and call it DoughnutsAndCoffee. Here is the designer file and the Code behind:
Code Behind:
Public Class DoughnutsAndCoffee
Private SelectedItems As New List(Of Items)
Public Event ItemsChanged()
Public Sub UpdateTotal() Handles Me.ItemsChanged
Dim subTotal As Decimal = 0D
For Each item As Items In SelectedItems
subTotal += Prices.GetPrice(item)
Next
Dim TaxTotal As Decimal = subTotal * Prices.Tax_Rate
Dim total As Decimal = subTotal + TaxTotal
Me.SubTotal_Label.Invoke(Sub() Me.SubTotal_Label.Text = subTotal.ToString("C2"))
Me.Tax_Label.Invoke(Sub() Me.Tax_Label.Text = TaxTotal.ToString("C2"))
Me.Total_Label.Invoke(Sub() Me.Total_Label.Text = total.ToString("C2"))
End Sub
Private Sub RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles Cappuccino_RadioButton.CheckedChanged, Chocolate_RadioButton.CheckedChanged, Filled_RadioButton.CheckedChanged, Glazed_RadioButton.CheckedChanged, Regular_RadioButton.CheckedChanged, Sugar_RadioButton.CheckedChanged
Dim senderRB As RadioButton = DirectCast(sender, RadioButton)
Dim selectedItem As String = (From item As String In GetType(Items).GetEnumNames Where senderRB.Name.Contains(item) Select item).FirstOrDefault
If selectedItem <> String.Empty Then
Dim Item As Items = DirectCast([Enum].Parse(GetType(Items), selectedItem), Items)
If senderRB.Checked Then
Me.SelectedItems.Add(Item)
RaiseEvent ItemsChanged()
Else
If Me.SelectedItems.Contains(Item) Then
Me.SelectedItems.Remove(Item)
RaiseEvent ItemsChanged()
End If
End If
End If
End Sub
Private Sub DoughnutsAndCoffee_Shown(sender As Object, e As EventArgs) Handles Me.Shown
RaiseEvent ItemsChanged()
End Sub
End Class
Public Structure Prices
Public Const Tax_Rate As Decimal = 0.03D
Public Const Glazed As Decimal = 0.65D
Public Const Sugar As Decimal = 0.65D
Public Const Chocolate As Decimal = 0.85D
Public Const Filled As Decimal = 1D
Public Const Regular As Decimal = 1D
Public Const Cappuccino As Decimal = 2.5D
Public Shared Function GetPrice(item As Items) As Decimal
Dim itemStr As String = [Enum].GetName(GetType(Items), item)
Return GetType(Prices).GetField(itemStr).GetValue(Nothing)
End Function
End Structure
Public Enum Items
Glazed
Sugar
Chocolate
Filled
Regular
Cappuccino
End Enum
Designer File:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class DoughnutsAndCoffee
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Glazed_RadioButton = New System.Windows.Forms.RadioButton()
Me.Sugar_RadioButton = New System.Windows.Forms.RadioButton()
Me.Chocolate_RadioButton = New System.Windows.Forms.RadioButton()
Me.Filled_RadioButton = New System.Windows.Forms.RadioButton()
Me.Regular_RadioButton = New System.Windows.Forms.RadioButton()
Me.Cappuccino_RadioButton = New System.Windows.Forms.RadioButton()
Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel()
Me.Total_Label = New System.Windows.Forms.Label()
Me.Label5 = New System.Windows.Forms.Label()
Me.Tax_Label = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.SubTotal_Label = New System.Windows.Forms.Label()
Me.Label1 = New System.Windows.Forms.Label()
Me.FlowLayoutPanel2 = New System.Windows.Forms.FlowLayoutPanel()
Me.FlowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel()
Me.Coffee_GroupBox = New System.Windows.Forms.GroupBox()
Me.Doughnuts_GroupBox = New System.Windows.Forms.GroupBox()
Me.TableLayoutPanel1.SuspendLayout()
Me.FlowLayoutPanel2.SuspendLayout()
Me.FlowLayoutPanel1.SuspendLayout()
Me.Coffee_GroupBox.SuspendLayout()
Me.Doughnuts_GroupBox.SuspendLayout()
Me.SuspendLayout()
'
'Glazed_RadioButton
'
Me.Glazed_RadioButton.AutoSize = True
Me.Glazed_RadioButton.Location = New System.Drawing.Point(3, 3)
Me.Glazed_RadioButton.Name = "Glazed_RadioButton"
Me.Glazed_RadioButton.Size = New System.Drawing.Size(58, 17)
Me.Glazed_RadioButton.TabIndex = 9
Me.Glazed_RadioButton.Text = "Glazed"
Me.Glazed_RadioButton.UseVisualStyleBackColor = True
'
'Sugar_RadioButton
'
Me.Sugar_RadioButton.AutoSize = True
Me.Sugar_RadioButton.Location = New System.Drawing.Point(3, 26)
Me.Sugar_RadioButton.Name = "Sugar_RadioButton"
Me.Sugar_RadioButton.Size = New System.Drawing.Size(53, 17)
Me.Sugar_RadioButton.TabIndex = 10
Me.Sugar_RadioButton.Text = "Sugar"
Me.Sugar_RadioButton.UseVisualStyleBackColor = True
'
'Chocolate_RadioButton
'
Me.Chocolate_RadioButton.AutoSize = True
Me.Chocolate_RadioButton.Location = New System.Drawing.Point(3, 49)
Me.Chocolate_RadioButton.Name = "Chocolate_RadioButton"
Me.Chocolate_RadioButton.Size = New System.Drawing.Size(73, 17)
Me.Chocolate_RadioButton.TabIndex = 11
Me.Chocolate_RadioButton.Text = "Chocolate"
Me.Chocolate_RadioButton.UseVisualStyleBackColor = True
'
'Filled_RadioButton
'
Me.Filled_RadioButton.AutoSize = True
Me.Filled_RadioButton.Location = New System.Drawing.Point(3, 72)
Me.Filled_RadioButton.Name = "Filled_RadioButton"
Me.Filled_RadioButton.Size = New System.Drawing.Size(49, 17)
Me.Filled_RadioButton.TabIndex = 12
Me.Filled_RadioButton.Text = "Filled"
Me.Filled_RadioButton.UseVisualStyleBackColor = True
'
'Regular_RadioButton
'
Me.Regular_RadioButton.AutoSize = True
Me.Regular_RadioButton.Location = New System.Drawing.Point(3, 3)
Me.Regular_RadioButton.Name = "Regular_RadioButton"
Me.Regular_RadioButton.Size = New System.Drawing.Size(62, 17)
Me.Regular_RadioButton.TabIndex = 13
Me.Regular_RadioButton.Text = "Regular"
Me.Regular_RadioButton.UseVisualStyleBackColor = True
'
'Cappuccino_RadioButton
'
Me.Cappuccino_RadioButton.AutoSize = True
Me.Cappuccino_RadioButton.Location = New System.Drawing.Point(3, 26)
Me.Cappuccino_RadioButton.Name = "Cappuccino_RadioButton"
Me.Cappuccino_RadioButton.Size = New System.Drawing.Size(82, 17)
Me.Cappuccino_RadioButton.TabIndex = 14
Me.Cappuccino_RadioButton.Text = "Cappuccino"
Me.Cappuccino_RadioButton.UseVisualStyleBackColor = True
'
'TableLayoutPanel1
'
Me.TableLayoutPanel1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TableLayoutPanel1.AutoSize = True
Me.TableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.TableLayoutPanel1.ColumnCount = 2
Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel1.Controls.Add(Me.Total_Label, 1, 2)
Me.TableLayoutPanel1.Controls.Add(Me.Label5, 0, 2)
Me.TableLayoutPanel1.Controls.Add(Me.Tax_Label, 1, 1)
Me.TableLayoutPanel1.Controls.Add(Me.Label3, 0, 1)
Me.TableLayoutPanel1.Controls.Add(Me.SubTotal_Label, 1, 0)
Me.TableLayoutPanel1.Controls.Add(Me.Label1, 0, 0)
Me.TableLayoutPanel1.Location = New System.Drawing.Point(67, 133)
Me.TableLayoutPanel1.Name = "TableLayoutPanel1"
Me.TableLayoutPanel1.RowCount = 3
Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333!))
Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333!))
Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333!))
Me.TableLayoutPanel1.Size = New System.Drawing.Size(140, 57)
Me.TableLayoutPanel1.TabIndex = 9
'
'Total_Label
'
Me.Total_Label.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Total_Label.AutoSize = True
Me.Total_Label.Location = New System.Drawing.Point(80, 41)
Me.Total_Label.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3)
Me.Total_Label.Name = "Total_Label"
Me.Total_Label.Size = New System.Drawing.Size(39, 13)
Me.Total_Label.TabIndex = 5
Me.Total_Label.Text = "Label6"
'
'Label5
'
Me.Label5.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Label5.AutoSize = True
Me.Label5.Location = New System.Drawing.Point(10, 41)
Me.Label5.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(31, 13)
Me.Label5.TabIndex = 4
Me.Label5.Text = "Total"
'
'Tax_Label
'
Me.Tax_Label.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Tax_Label.AutoSize = True
Me.Tax_Label.Location = New System.Drawing.Point(80, 22)
Me.Tax_Label.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3)
Me.Tax_Label.Name = "Tax_Label"
Me.Tax_Label.Size = New System.Drawing.Size(39, 13)
Me.Tax_Label.TabIndex = 3
Me.Tax_Label.Text = "Label4"
'
'Label3
'
Me.Label3.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(10, 22)
Me.Label3.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(25, 13)
Me.Label3.TabIndex = 2
Me.Label3.Text = "Tax"
'
'SubTotal_Label
'
Me.SubTotal_Label.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.SubTotal_Label.AutoSize = True
Me.SubTotal_Label.Location = New System.Drawing.Point(80, 3)
Me.SubTotal_Label.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3)
Me.SubTotal_Label.Name = "SubTotal_Label"
Me.SubTotal_Label.Size = New System.Drawing.Size(39, 13)
Me.SubTotal_Label.TabIndex = 1
Me.SubTotal_Label.Text = "Label2"
'
'Label1
'
Me.Label1.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(10, 3)
Me.Label1.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(50, 13)
Me.Label1.TabIndex = 0
Me.Label1.Text = "SubTotal"%0
I've updated a project from VB6 to VB.NET. Everything seemed to work fine, but now I'm facing errors related to the namespace when trying to build. Besides, I'm getting them on Form's designers, which have been automatically generated by Visual Studio. More specifically, the errors I'm facing involve the System.Drawing namespace and its internal structures (Point, Size, SizeF, etc).
I've checked it and I haven't found any other class that could be causing the conflict. I've also tried to delete the reference to the library and add it again, and to Clean the project, but the error is still there.
It's seems a problem similar to the one asked in this question, but I've tried the solutions answered there and haven't worked either. Any ideas of what could I do? This is driving me crazy and my whole project is stopped until I can fix that.
Thank you very, very much in advance.
EDIT: Added screenshots of the error and the code that's throwing it
Complete message of one of the errors: Error 18 'Point' is ambiguous in the namespace 'System.Drawing'. C:\Users\practiquesINF\Desktop\Projecte01_VBNET_V2\Upgraded\Frm_Files.Designer.vb 152 39 P_IF01
Complete code of one of the files that throws the error (as I've said, it's the designer of one of the forms and it has been generated automatically):
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Frm_Files
#Region "Upgrade Support "
Private Shared m_vb6FormDefInstance As Frm_Files
Private Shared m_InitializingDefInstance As Boolean
Public Shared Property DefInstance() As Frm_Files
Get
If m_vb6FormDefInstance Is Nothing OrElse m_vb6FormDefInstance.IsDisposed Then
m_InitializingDefInstance = True
m_vb6FormDefInstance = CreateInstance()
m_InitializingDefInstance = False
End If
Return m_vb6FormDefInstance
End Get
Set(ByVal Value As Frm_Files)
m_vb6FormDefInstance = Value
End Set
End Property
#End Region
#Region "Windows Form Designer generated code "
Public Shared Function CreateInstance() As Frm_Files
Dim theInstance As Frm_Files = New Frm_Files()
theInstance.Form_Load()
Return theInstance
End Function
Private visualControls() As String = New String() {"components", "ToolTipMain", "_Text1_4", "DataCombo1", "_Text1_3", "_Text1_2", "_Command1_2", "_Command1_1", "_Text1_1", "_Text1_0", "_Command1_0", "CommonDialog1Open", "_Label1_6", "_Label1_5", "_Label1_4", "_Label1_3", "_Label1_2", "_Label1_1", "_Label1_0", "Command1", "Label1", "Text1"}
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Public ToolTipMain As System.Windows.Forms.ToolTip
Private WithEvents _Text1_4 As System.Windows.Forms.TextBox
Public WithEvents DataCombo1 As AxMSDataListLib.AxDataCombo
Private WithEvents _Text1_3 As System.Windows.Forms.TextBox
Private WithEvents _Text1_2 As System.Windows.Forms.TextBox
Private WithEvents _Command1_2 As System.Windows.Forms.Button
Private WithEvents _Command1_1 As System.Windows.Forms.Button
Private WithEvents _Text1_1 As System.Windows.Forms.TextBox
Private WithEvents _Text1_0 As System.Windows.Forms.TextBox
Private WithEvents _Command1_0 As System.Windows.Forms.Button
Public WithEvents CommonDialog1Open As System.Windows.Forms.OpenFileDialog
Private WithEvents _Label1_6 As System.Windows.Forms.Label
Private WithEvents _Label1_5 As System.Windows.Forms.Label
Private WithEvents _Label1_4 As System.Windows.Forms.Label
Private WithEvents _Label1_3 As System.Windows.Forms.Label
Private WithEvents _Label1_2 As System.Windows.Forms.Label
Private WithEvents _Label1_1 As System.Windows.Forms.Label
Private WithEvents _Label1_0 As System.Windows.Forms.Label
Public Command1(2) As System.Windows.Forms.Button
Public Label1(6) As System.Windows.Forms.Label
Public Text1(4) As System.Windows.Forms.TextBox
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Frm_Files))
Me.ToolTipMain = New System.Windows.Forms.ToolTip(Me.components)
Me._Text1_4 = New System.Windows.Forms.TextBox()
Me.DataCombo1 = New AxMSDataListLib.AxDataCombo()
Me._Text1_3 = New System.Windows.Forms.TextBox()
Me._Text1_2 = New System.Windows.Forms.TextBox()
Me._Command1_2 = New System.Windows.Forms.Button()
Me._Command1_1 = New System.Windows.Forms.Button()
Me._Text1_1 = New System.Windows.Forms.TextBox()
Me._Text1_0 = New System.Windows.Forms.TextBox()
Me._Command1_0 = New System.Windows.Forms.Button()
Me.CommonDialog1Open = New System.Windows.Forms.OpenFileDialog()
Me._Label1_6 = New System.Windows.Forms.Label()
Me._Label1_5 = New System.Windows.Forms.Label()
Me._Label1_4 = New System.Windows.Forms.Label()
Me._Label1_3 = New System.Windows.Forms.Label()
Me._Label1_2 = New System.Windows.Forms.Label()
Me._Label1_1 = New System.Windows.Forms.Label()
Me._Label1_0 = New System.Windows.Forms.Label()
CType(Me.DataCombo1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'_Text1_4
'
Me._Text1_4.AcceptsReturn = True
Me._Text1_4.BackColor = System.Drawing.SystemColors.Window
Me._Text1_4.Cursor = System.Windows.Forms.Cursors.IBeam
Me._Text1_4.ForeColor = System.Drawing.SystemColors.WindowText
Me._Text1_4.Location = New System.Drawing.Point(160, 200)
Me._Text1_4.MaxLength = 1
Me._Text1_4.Name = "_Text1_4"
Me._Text1_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Text1_4.Size = System.Drawing.Size(19, 20)
Me._Text1_4.TabIndex = 14
Me._Text1_4.Text = "S"
Me._Text1_4.Visible = False
'
'DataCombo1
'
Me.DataCombo1.Location = New System.Drawing.Point(112, 240)
Me.DataCombo1.Name = "DataCombo1"
Me.DataCombo1.OcxState = CType(resources.GetObject("DataCombo1.OcxState"), System.Windows.Forms.AxHost.State)
' Me.DataCombo1.RowSource = Nothing HI HA QUE AFEGIR UN DATA SOURCE O SINO EL PROBLEMA NO GENERA EL FORMULARI
Me.DataCombo1.Size = New System.Drawing.Size(233, 21)
Me.DataCombo1.TabIndex = 13
'
'_Text1_3
'
Me._Text1_3.AcceptsReturn = True
Me._Text1_3.BackColor = System.Drawing.SystemColors.Window
Me._Text1_3.Cursor = System.Windows.Forms.Cursors.IBeam
Me._Text1_3.ForeColor = System.Drawing.SystemColors.WindowText
Me._Text1_3.Location = New System.Drawing.Point(270, 112)
Me._Text1_3.MaxLength = 0
Me._Text1_3.Name = "_Text1_3"
Me._Text1_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Text1_3.Size = New System.Drawing.Size(67, 20)
Me._Text1_3.TabIndex = 10
Me._Text1_3.Text = "19"
Me._Text1_3.Visible = False
'
'_Text1_2
'
Me._Text1_2.AcceptsReturn = True
Me._Text1_2.BackColor = System.Drawing.SystemColors.Window
Me._Text1_2.Cursor = System.Windows.Forms.Cursors.IBeam
Me._Text1_2.ForeColor = System.Drawing.SystemColors.WindowText
Me._Text1_2.Location = New System.Drawing.Point(113, 111)
Me._Text1_2.MaxLength = 0
Me._Text1_2.Name = "_Text1_2"
Me._Text1_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Text1_2.Size = New System.Drawing.Size(43, 20)
Me._Text1_2.TabIndex = 8
Me._Text1_2.Text = "32"
Me._Text1_2.Visible = False
'
'_Command1_2
'
Me._Command1_2.BackColor = System.Drawing.SystemColors.Control
Me._Command1_2.Cursor = System.Windows.Forms.Cursors.Default
Me._Command1_2.ForeColor = System.Drawing.SystemColors.ControlText
Me._Command1_2.Location = New System.Drawing.Point(155, 272)
Me._Command1_2.Name = "_Command1_2"
Me._Command1_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Command1_2.Size = New System.Drawing.Size(78, 33)
Me._Command1_2.TabIndex = 6
Me._Command1_2.Text = "Cancel"
Me._Command1_2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me._Command1_2.UseVisualStyleBackColor = False
'
'_Command1_1
'
Me._Command1_1.BackColor = System.Drawing.SystemColors.Control
Me._Command1_1.Cursor = System.Windows.Forms.Cursors.Default
Me._Command1_1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me._Command1_1.ForeColor = System.Drawing.SystemColors.ControlText
Me._Command1_1.Location = New System.Drawing.Point(245, 266)
Me._Command1_1.Name = "_Command1_1"
Me._Command1_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Command1_1.Size = New System.Drawing.Size(97, 40)
Me._Command1_1.TabIndex = 5
Me._Command1_1.Text = "OK"
Me._Command1_1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me._Command1_1.UseVisualStyleBackColor = False
'
'_Text1_1
'
Me._Text1_1.AcceptsReturn = True
Me._Text1_1.BackColor = System.Drawing.SystemColors.Window
Me._Text1_1.Cursor = System.Windows.Forms.Cursors.IBeam
Me._Text1_1.ForeColor = System.Drawing.SystemColors.WindowText
Me._Text1_1.Location = New System.Drawing.Point(114, 82)
Me._Text1_1.MaxLength = 0
Me._Text1_1.Name = "_Text1_1"
Me._Text1_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Text1_1.Size = New System.Drawing.Size(225, 20)
Me._Text1_1.TabIndex = 2
Me._Text1_1.Text = "c:\cgc\RUSTICA.TXT"
'
'_Text1_0
'
Me._Text1_0.AcceptsReturn = True
Me._Text1_0.BackColor = System.Drawing.SystemColors.Window
Me._Text1_0.Cursor = System.Windows.Forms.Cursors.IBeam
Me._Text1_0.ForeColor = System.Drawing.SystemColors.WindowText
Me._Text1_0.Location = New System.Drawing.Point(113, 53)
Me._Text1_0.MaxLength = 0
Me._Text1_0.Name = "_Text1_0"
Me._Text1_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Text1_0.Size = New System.Drawing.Size(225, 20)
Me._Text1_0.TabIndex = 1
Me._Text1_0.Text = "c:\cgc\240padrus.cnt"
'
'_Command1_0
'
Me._Command1_0.BackColor = System.Drawing.SystemColors.Control
Me._Command1_0.Cursor = System.Windows.Forms.Cursors.Default
Me._Command1_0.ForeColor = System.Drawing.SystemColors.ControlText
Me._Command1_0.Location = New System.Drawing.Point(248, 7)
Me._Command1_0.Name = "_Command1_0"
Me._Command1_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Command1_0.Size = New System.Drawing.Size(91, 38)
Me._Command1_0.TabIndex = 0
Me._Command1_0.Text = "Buscar Fitxer"
Me._Command1_0.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me._Command1_0.UseVisualStyleBackColor = False
'
'CommonDialog1Open
'
'
'_Label1_6
'
Me._Label1_6.BackColor = System.Drawing.SystemColors.Control
Me._Label1_6.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_6.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_6.Location = New System.Drawing.Point(8, 205)
Me._Label1_6.Name = "_Label1_6"
Me._Label1_6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_6.Size = New System.Drawing.Size(137, 23)
Me._Label1_6.TabIndex = 15
Me._Label1_6.Text = "Firma Secretari (S/N):"
Me._Label1_6.Visible = False
'
'_Label1_5
'
Me._Label1_5.BackColor = System.Drawing.SystemColors.Control
Me._Label1_5.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_5.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_5.Location = New System.Drawing.Point(8, 248)
Me._Label1_5.Name = "_Label1_5"
Me._Label1_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_5.Size = New System.Drawing.Size(97, 23)
Me._Label1_5.TabIndex = 12
Me._Label1_5.Text = "Remesa:"
Me._Label1_5.Visible = False
'
'_Label1_4
'
Me._Label1_4.BackColor = System.Drawing.SystemColors.Control
Me._Label1_4.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_4.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_4.Location = New System.Drawing.Point(8, 24)
Me._Label1_4.Name = "_Label1_4"
Me._Label1_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_4.Size = New System.Drawing.Size(91, 19)
Me._Label1_4.TabIndex = 11
Me._Label1_4.Text = "Banc"
Me._Label1_4.Visible = False
'
'_Label1_3
'
Me._Label1_3.BackColor = System.Drawing.SystemColors.Control
Me._Label1_3.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_3.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_3.Location = New System.Drawing.Point(171, 112)
Me._Label1_3.Name = "_Label1_3"
Me._Label1_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_3.Size = New System.Drawing.Size(99, 19)
Me._Label1_3.TabIndex = 9
Me._Label1_3.Text = "Pes de les Cartes:"
Me._Label1_3.Visible = False
'
'_Label1_2
'
Me._Label1_2.BackColor = System.Drawing.SystemColors.Control
Me._Label1_2.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_2.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_2.Location = New System.Drawing.Point(8, 116)
Me._Label1_2.Name = "_Label1_2"
Me._Label1_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_2.Size = New System.Drawing.Size(97, 23)
Me._Label1_2.TabIndex = 7
Me._Label1_2.Text = "Remesa:"
Me._Label1_2.Visible = False
'
'_Label1_1
'
Me._Label1_1.BackColor = System.Drawing.SystemColors.Control
Me._Label1_1.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_1.Location = New System.Drawing.Point(8, 85)
Me._Label1_1.Name = "_Label1_1"
Me._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_1.Size = New Drawing.Size(97, 23)
Me._Label1_1.TabIndex = 4
Me._Label1_1.Text = "Fitxer d'Eixida:"
'
'_Label1_0
'
Me._Label1_0.BackColor = System.Drawing.SystemColors.Control
Me._Label1_0.Cursor = System.Windows.Forms.Cursors.Default
Me._Label1_0.ForeColor = System.Drawing.SystemColors.ControlText
Me._Label1_0.Location = New System.Drawing.Point(8, 55)
Me._Label1_0.Name = "_Label1_0"
Me._Label1_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._Label1_0.Size = New System.Drawing.Size(97, 22)
Me._Label1_0.TabIndex = 3
Me._Label1_0.Text = "Fitxer d'Entrada:"
'
'Frm_Files
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.Control
Me.ClientSize = New System.Drawing.Size(364, 324)
Me.Controls.Add(Me._Text1_4)
Me.Controls.Add(Me.DataCombo1)
Me.Controls.Add(Me._Text1_3)
Me.Controls.Add(Me._Text1_2)
Me.Controls.Add(Me._Command1_2)
Me.Controls.Add(Me._Command1_1)
Me.Controls.Add(Me._Text1_1)
Me.Controls.Add(Me._Text1_0)
Me.Controls.Add(Me._Command1_0)
Me.Controls.Add(Me._Label1_6)
Me.Controls.Add(Me._Label1_5)
Me.Controls.Add(Me._Label1_4)
Me.Controls.Add(Me._Label1_3)
Me.Controls.Add(Me._Label1_2)
Me.Controls.Add(Me._Label1_1)
Me.Controls.Add(Me._Label1_0)
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.Location = New System.Drawing.Point(3, 18)
Me.Name = "Frm_Files"
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Text = "Fitxers d'entrada i Eixida"
CType(Me.DataCombo1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Sub ReLoadForm(ByVal addEvents As Boolean)
InitializeText1()
InitializeLabel1()
InitializeCommand1()
Form_Load()
If addEvents Then
AddHandler MyBase.Closed, AddressOf Me.Frm_Files_Closed
End If
End Sub
Sub InitializeText1()
ReDim Text1(4)
Me.Text1(4) = _Text1_4
Me.Text1(3) = _Text1_3
Me.Text1(2) = _Text1_2
Me.Text1(1) = _Text1_1
Me.Text1(0) = _Text1_0
End Sub
Sub InitializeLabel1()
ReDim Label1(6)
Me.Label1(6) = _Label1_6
Me.Label1(5) = _Label1_5
Me.Label1(4) = _Label1_4
Me.Label1(3) = _Label1_3
Me.Label1(2) = _Label1_2
Me.Label1(1) = _Label1_1
Me.Label1(0) = _Label1_0
End Sub
Sub InitializeCommand1()
ReDim Command1(2)
Me.Command1(2) = _Command1_2
Me.Command1(1) = _Command1_1
Me.Command1(0) = _Command1_0
End Sub
#End Region
End Class
In case this is relevant for the question, the form was upgraded from VB6 to VB.NET using an automatic tool. Specifically, the VBUC by Mobilize.net (I do not intend to do this as spam, but to give as much information as I can. If I shouldn't have done this, I'll edit the post and delete the reference)
Finally, I've managed to solve it! It seems that one of the external libraries I was using was creating a conflict. As Visual Studio didn't tell my which one it was, I simply unreferenced them all and then referenced again only the ones that I needed at that exact moment.
The conflict seemed to be caused by one of the libraries of the GrapeCity's ActiveReport tool. As I had to upgrade the tool and it wasn't code that I had written (and it was quite poorly commented), I didn't know which ones were or will be needed, so I referenced more than necessary. And it seems that precisely one of the extra libraries (I'm not sure at all, but I think that it was one of the Chart ones) was the one causing the conflict.
Thank you all for your help! And sorry for not answering before, but I had to switch to another urgent project and I couldn't try the solutions until today.
I have a winforms DataGridView that I wish to have a column containing comboboxes for each record. Each combobox will have completely different values for each row and need to be assigned a datasource during the databinding of the DataGridView. I can assign 1 datasource to all (that's easy), but having each combobox have different values looks impossible).
Here's what I'm working with - note: The datasource of the DataGridView is defined programmatically by setting a property from the calling form.
Public Class frmSendToQuickbooksPopup
Public Property CurrentOrder As OrderICT
Public Property lineitems As List(Of OrderLineItemICT)
Private Sub frmSendToQuickbooksPopup_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'define the combobox (datasource can't be assigned here as each will be different for each row)
Dim dgvcboMatch As New DataGridViewComboBoxColumn
dgvcboMatch.DisplayMember = "Name"
dgvcboMatch.ValueMember = "ListID"
dgvcboMatch.HeaderText = "Matches"
dgvcboMatch.Name = "Match"
dgvcboMatch.Width = 150
dgvLineItems.Columns.Add(dgvcboMatch)
Me.dgvLineItems.DataSource = lineitems
End Sub
Private Sub dgvLineItems_DataSourceChanged(sender As Object, e As EventArgs) Handles dgvLineItems.DataSourceChanged
Dim L As New QBI.OrderLineItemICT
With L
dgvLineItems.Columns(.col_LineItemBvin).Visible = False
dgvLineItems.Columns(.col_ProductId).Visible = False
dgvLineItems.Columns(.col_ProductShortDescription).Visible = False
dgvLineItems.Columns(.col_ShippingBoxCount).Visible = False
dgvLineItems.Columns(.col_CustomProperties).Visible = False
dgvLineItems.Columns(.col_ShippingLength).Visible = False
dgvLineItems.Columns(.col_ShippingWidth).Visible = False
dgvLineItems.Columns(.col_ShippingHeight).Visible = False
dgvLineItems.Columns(.col_ProductName).DisplayIndex = 2
dgvLineItems.Columns(.col_ProductName).HeaderText = "Product Name"
dgvLineItems.Columns(.col_ProductName).Width = 170
dgvLineItems.Columns(.col_ProductSku).HeaderText = "SKU"
dgvLineItems.Columns(.col_ProductSku).Width = 160
dgvLineItems.Columns(.col_Quantity).DefaultCellStyle.Format = "n0"
dgvLineItems.Columns(.col_Quantity).DisplayIndex = 7
dgvLineItems.Columns(.col_Quantity).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
dgvLineItems.Columns(.col_Quantity).Width = 65
dgvLineItems.Columns(.col_AdjustedPrice).DefaultCellStyle.Format = "c2"
dgvLineItems.Columns(.col_AdjustedPrice).HeaderText = "Adj Price"
dgvLineItems.Columns(.col_AdjustedPrice).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvLineItems.Columns(.col_AdjustedPrice).Width = 80
dgvLineItems.Columns(.col_BasePrice).DefaultCellStyle.Format = "c2"
dgvLineItems.Columns(.col_BasePrice).HeaderText = "Base Price"
dgvLineItems.Columns(.col_BasePrice).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvLineItems.Columns(.col_BasePrice).Width = 85
dgvLineItems.Columns(.col_Discounts).DefaultCellStyle.Format = "c2"
dgvLineItems.Columns(.col_Discounts).HeaderText = "Discounts"
dgvLineItems.Columns(.col_Discounts).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvLineItems.Columns(.col_Discounts).Width = 80
dgvLineItems.Columns(.col_LineTotal).DefaultCellStyle.Format = "c2"
dgvLineItems.Columns(.col_LineTotal).HeaderText = "Line Total"
dgvLineItems.Columns(.col_LineTotal).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvLineItems.Columns(.col_LineTotal).Width = 80
dgvLineItems.Columns(.col_UOM).DisplayIndex = 9
dgvLineItems.Columns(.col_UOM).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
dgvLineItems.Columns(.col_UOM).HeaderText = "Units"
dgvLineItems.Columns(.col_UOM).Width = 55
dgvLineItems.Columns(.col_ShippingWeight).DisplayIndex = 10
dgvLineItems.Columns(.col_ShippingWeight).HeaderText = "Unit Wt"
dgvLineItems.Columns(.col_ShippingWeight).DefaultCellStyle.Format = "N1"
dgvLineItems.Columns(.col_ShippingWeight).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvLineItems.Columns(.col_ShippingWeight).Width = 70
End With
End Sub
Public Function GetComboboxData(ProductNameToMatch As String, ProductSKUToMatch As String) As List(Of WPM_Item)
'this function returns a list of returned matches for a given row's ProductName or SKU
'this function will be the datasource for a given combobox
Dim itms As New List(Of WPM_Item)
itms = WPM_Data.FindWPM_ItemMatch(ProductNameToMatch, ProductSKUToMatch)
Return itms
End Function
End Class
If there were some way to intercept the databinding of the DataGridView so I can get a value from another cell (to call another procedure), then use the return data to populate each row's combobox. This is easy w/webforms, but I don't see an event for the winforms version.
Another thing I've tried, but does not work (the combobox datasource just disappears!)
Private Sub dgvLineItems_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles dgvLineItems.DataBindingComplete
For Each row As DataGridViewRow In Me.dgvLineItems.Rows
Dim dr = DirectCast(row.DataBoundItem, OrderLineItemICT)
If dr Is Nothing Then
Return
End If
Dim name As String = row.Cells(dr.col_ProductName).Value.ToString
Dim SKU As String = row.Cells(dr.col_ProductSku).Value.ToString
Dim cell As DataGridViewComboBoxCell = TryCast(row.Cells("Match"), DataGridViewComboBoxCell)
cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
Dim wpm_items As List(Of WPM_Item) = GetComboboxData(name, SKU)
If cell.DataSource Is Nothing Then
cell.DataSource = wpm_items 'this forgets the datasource, why?
cell.DisplayMember = "Name"
cell.ValueMember = "ListID"
cell.Value = wpm_items.Item(0).Name 'this always throws an error "DataGridViewComboBoxCell value is not valid."
End If
Next
End Sub
Here's another version of that same assignment, this time the combobox is populated with the add method. (STILL does not remember the values)
I basically followed another forum's idea - maybe DotNet 4.5 DataGridView has a bug in it.
Private Sub dgvLineItems_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles dgvLineItems.DataBindingComplete
For Each row As DataGridViewRow In Me.dgvLineItems.Rows
Dim dr = DirectCast(row.DataBoundItem, OrderLineItemICT)
If dr Is Nothing Then
Return
End If
Dim name As String = row.Cells(dr.col_ProductName).Value.ToString
Dim SKU As String = row.Cells(dr.col_ProductSku).Value.ToString
Dim cell As DataGridViewComboBoxCell = DirectCast(row.Cells("Match"), DataGridViewComboBoxCell)
cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
Dim wpm_items As List(Of WPM_Item) = GetComboboxData(name, SKU)
'THIS DOES NOT WORK EITHER!!
cell.DisplayMember = "Name"
cell.ValueMember = "ListID"
For Each wItm As WPM_Item In wpm_items
Dim c As New comboboxitem
c.Text = wItm.Name
c.Value = wItm.ListID
cell.Items.Add(c)
Next
Next
End Sub
Public Class ComboboxItem
Public Property Text() As String
Public Property Value() As Object
Public Overrides Function ToString() As String
Return Text
End Function
End Class
Allrighty Then! Here's a working solution. What I discovered is that you must create your DataGridView programmatically (tedious, yes!) and turn off auto-generation of columns (absolute must) - this prevents multiple firings of dataGridView events, for one. It also prevents losing your datasource for your combobox. Using the DataBindingComplete event and parsing the rows within is the best way to do this (CellFormatting event is overkill and is called w/every mouse move, click, resize, etc).
For those of us working with objects instead of datatables, I hope this solution is usable.
The code:
Imports QBI
Imports QBI.QBI
Imports QBI.AppCore.Xutilities
Public Class TestDGV1
Public dgv1 As DataGridView
Private Sub TestDGV1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ordlineitems As List(Of OrderLineItemICT)
ordlineitems = Order_DataICT.GetNewOrderLineItemsICT("26073bff-3a08-4bc2-8da9-79c75534bd6b")
dgv1 = Me.CreateDGV(ordlineitems) 'create the DataGridView and save it as "dgv1" (which must be publically accessible)
Me.SplitContainer1.Panel2.Controls.Add(dgv1) 'NOTE, the datagridview is inside a SplitContainer
End Sub
Public Function CreateDGV(dsItems As List(Of OrderLineItemICT)) As DataGridView
Dim dgv As New DataGridView()
dgv.Dock = DockStyle.Fill
dgv.DataSource = dsItems
dgv.EditMode = DataGridViewEditMode.EditOnEnter
dgv.AutoGenerateColumns = False
dgv.AllowUserToAddRows = False
Dim L As New QBI.OrderLineItemICT 'only using this reference for my column names defined elsewhere
Dim col0 As New DataGridViewComboBoxColumn With {.Name = "Match", .DataPropertyName = "NameMatch", .DisplayMember = "Name", .ValueMember = "ListID", .HeaderText = "Matches", .AutoComplete = True}
col0.DisplayIndex = 0
Dim col1 As New DataGridViewTextBoxColumn With {.Name = L.col_LineItemBvin, .DataPropertyName = L.col_LineItemBvin, .Visible = False, .ReadOnly = True, .HeaderText = L.col_LineItemBvin}
col1.DisplayIndex = 1
Dim col2 As New DataGridViewTextBoxColumn With {.Name = L.col_ProductId, .DataPropertyName = L.col_ProductId, .Visible = False, .ReadOnly = True, .HeaderText = L.col_ProductId}
col2.DisplayIndex = 2
Dim col3 As New DataGridViewTextBoxColumn With {.Name = L.col_ProductSku, .DataPropertyName = L.col_ProductSku, .Visible = True, .ReadOnly = True, .HeaderText = "SKU"}
col3.DisplayIndex = 3
col3.Width = 160
Dim col4 As New DataGridViewTextBoxColumn With {.Name = L.col_Quantity, .DataPropertyName = L.col_Quantity, .Visible = True, .ReadOnly = True, .HeaderText = "QTY"}
col4.DisplayIndex = 9
col4.Width = 65
col4.DefaultCellStyle.Format = "n0"
col4.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
Dim col5 As New DataGridViewTextBoxColumn With {.Name = L.col_BasePrice, .DataPropertyName = L.col_BasePrice, .Visible = True, .ReadOnly = True, .HeaderText = "Base Price"}
col5.DisplayIndex = 6
col5.DefaultCellStyle.Format = "c2"
col5.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
col5.Width = 85
Dim col6 As New DataGridViewTextBoxColumn With {.Name = L.col_Discounts, .DataPropertyName = L.col_Discounts, .Visible = True, .ReadOnly = True, .HeaderText = "Discounts"}
col6.DisplayIndex = 7
col6.DefaultCellStyle.Format = "c2"
col6.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
col6.Width = 80
Dim col7 As New DataGridViewTextBoxColumn With {.Name = L.col_AdjustedPrice, .DataPropertyName = L.col_AdjustedPrice, .Visible = True, .ReadOnly = True, .HeaderText = "Adj Price"}
col7.DisplayIndex = 8
col7.DefaultCellStyle.Format = "c2"
col7.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
col7.Width = 80
Dim col8 As New DataGridViewTextBoxColumn With {.Name = L.col_LineTotal, .DataPropertyName = L.col_LineTotal, .Visible = True, .ReadOnly = True, .HeaderText = "Line Total"}
col8.DisplayIndex = 11
col8.DefaultCellStyle.Format = "c2"
col8.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
col8.Width = 80
Dim col9 As New DataGridViewTextBoxColumn With {.Name = L.col_ProductName, .DataPropertyName = L.col_ProductName, .Visible = True, .ReadOnly = True, .HeaderText = "Product Name"}
col9.DisplayIndex = 4
col9.Width = 170
Dim col10 As New DataGridViewTextBoxColumn With {.Name = L.col_ProductShortDescription, .DataPropertyName = L.col_ProductShortDescription, .Visible = False, .ReadOnly = True, .HeaderText = L.col_ProductShortDescription}
col10.DisplayIndex = 5
Dim col11 As New DataGridViewTextBoxColumn With {.Name = L.col_ShippingWeight, .DataPropertyName = L.col_ShippingWeight, .Visible = True, .ReadOnly = True, .HeaderText = "Unit Wt"}
col11.DisplayIndex = 12
col11.DefaultCellStyle.Format = "N1"
col11.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
col11.Width = 70
Dim col12 As New DataGridViewTextBoxColumn With {.Name = L.col_ShippingWidth, .DataPropertyName = L.col_ShippingWidth, .Visible = False, .ReadOnly = True, .HeaderText = L.col_ShippingWidth}
col12.DisplayIndex = 13
Dim col13 As New DataGridViewTextBoxColumn With {.Name = L.col_ShippingHeight, .DataPropertyName = L.col_ShippingHeight, .Visible = False, .ReadOnly = True, .HeaderText = L.col_ShippingHeight}
col13.DisplayIndex = 14
Dim col14 As New DataGridViewTextBoxColumn With {.Name = L.col_ShippingBoxCount, .DataPropertyName = L.col_ShippingBoxCount, .Visible = False, .ReadOnly = True, .HeaderText = L.col_ShippingBoxCount}
col14.DisplayIndex = 15
Dim col15 As New DataGridViewTextBoxColumn With {.Name = L.col_CustomProperties, .DataPropertyName = L.col_CustomProperties, .Visible = False, .ReadOnly = True, .HeaderText = L.col_CustomProperties}
col15.DisplayIndex = 16
Dim col16 As New DataGridViewTextBoxColumn With {.Name = L.col_UOM, .DataPropertyName = L.col_UOM, .Visible = True, .ReadOnly = True, .HeaderText = "Units"}
col16.DisplayIndex = 10
col16.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
col16.Width = 55
dgv.Columns.AddRange({col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16})
AddHandler dgv.DataBindingComplete, AddressOf dgvLineItems_DataBindingComplete
Return dgv
End Function
Private Sub dgvLineItems_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs)
For Each row As DataGridViewRow In Me.dgv1.Rows
Dim dr = DirectCast(row.DataBoundItem, OrderLineItemICT)
If dr Is Nothing Then
Return
End If
Dim name As String = row.Cells(dr.col_ProductName).Value.ToString
Dim SKU As String = row.Cells(dr.col_ProductSku).Value.ToString
Dim cell As DataGridViewComboBoxCell = DirectCast(row.Cells("Match"), DataGridViewComboBoxCell)
Dim wpm_items As List(Of WPM_Item) = GetComboboxData(name, SKU) 'function inside
If cell.DataSource Is Nothing Then
cell.DataSource = wpm_items
cell.DisplayMember = "Name"
cell.ValueMember = "ListID"
cell.Value = cell.Items(0).ListID
End If
Next
End Sub
Public Function GetComboboxData(ProductNameToMatch As String, ProductSKUToMatch As String) As List(Of WPM_Item)
'this function returns a list of returned matches for a given row's ProductName or SKU
'this function will be the datasource for a given combobox
Dim itms As New List(Of WPM_Item)
itms = WPM_Data.FindWPM_ItemMatch(ProductNameToMatch, ProductSKUToMatch)
Return itms
End Function
End Class
Here's an example in C# on how to have a DataGridViewComboBoxColumn in a DataGridView with different Types.
public static class ComboColumnDemo {
public static DataGridView CreateSampleDGV() {
DataTable table = new DataTable();
table.Columns.Add("VariableType", typeof(String));
table.Columns.Add("VariableId", typeof(int));
table.Columns.Add("Custom", typeof(Object));
table.Columns.Add("Default", typeof(Object));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(new Object[] { "int", 0, null, null, DateTime.MinValue });
table.Rows.Add(new Object[] { "decimal", 0, null, null, DateTime.MinValue });
table.Rows.Add(new Object[] { "enum", 0, null, null, DateTime.Now });
table.Rows.Add(new Object[] { "date", 0, null, null, DateTime.UtcNow });
table.Rows.Add(new Object[] { "person", 0, null, null, DateTime.Today });
table.Rows.Add(new Object[] { "String", 0, null, null, DateTime.MaxValue });
DataGridView dgv = new DataGridView();
dgv.Dock = DockStyle.Fill;
dgv.DataSource = table;
dgv.EditMode = DataGridViewEditMode.EditOnEnter;
dgv.AutoGenerateColumns = false;
dgv.AllowUserToAddRows = false;
DataGridViewComboBoxColumn colComboDefault = new DataGridViewComboBoxColumn { DataPropertyName = "Default", MaxDropDownItems = 20 };
//col2.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; //.DropDownButton;
colComboDefault.AutoComplete = true;
colComboDefault.ValueType = typeof(Object);
dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "VariableType" });
dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "VariableId" });
dgv.Columns.Add(colComboDefault);
dgv.Columns.Add(new CalendarColumn { DataPropertyName = "Date" });
foreach (DataGridViewColumn c in dgv.Columns)
c.HeaderText = c.DataPropertyName;
List<Object> strings = new List<Object>(new [] { "a", "b", "c" });
var ints = new List<Object>(new Object[] { DBNull.Value, 1, 2, 3 });
var decimals = new List<Object>(new Object[] { 1111111m, 2222222m, 3333333m });
List<Object> dates = new List<Object>(new Object[] { DBNull.Value, DateTime.Today });
List<Object> enums = new List<object>();
enums.Add(DBNull.Value);
enums.AddRange(Enum.GetValues(typeof(DayOfWeek)).Cast<Object>().ToArray());
DataTable enumsTable = Opulos.Core.Utils.EnumUtil<DayOfWeek>.ToDataTable();
List<Person> persons = new List<Person>();
dgv.CellFormatting += (sender, e) => {
var drv = (DataRowView) dgv.Rows[e.RowIndex].DataBoundItem;
if (drv == null)
return;
DataRow dr = drv.Row;
//String colName = dgv.Columns[col2].DataPropertyName;
String vt = (String) dr["VariableType"]; //table.Rows[row][0].ToString();
if (vt == "decimal" && e.ColumnIndex == 2) {
if (e.Value is decimal) {
e.Value = ((decimal) e.Value).ToString("n0");
e.FormattingApplied = true;
}
}
};
dgv.CellBeginEdit += (sender, e) => {
//dgv.EditingControlShowing += delegate {
int rowIndex = e.RowIndex;//dgv.CurrentCell.RowIndex;
int colIndex = e.ColumnIndex; //dgv.CurrentCell.ColumnIndex;
DataGridViewColumn col = dgv.Columns[colIndex];
try {
var drv = (DataRowView) dgv.Rows[rowIndex].DataBoundItem;
if (drv == null)
return;
DataRow dr = drv.Row;
//String colName = dgv.Columns[col2].DataPropertyName;
String vt = (String) dr["VariableType"]; //table.Rows[row][0].ToString();
//String vt = vm.VariableType;
Object items = null;
ComboBoxStyle? style = null;
Type valueType = null;
String formatString = null;
String displayMember = null;
String valueMember = null;
if (vt == "String") {
items = strings;
valueType = typeof(String);
}
else if (vt == "int") {
items = ints;
valueType = typeof(int);
}
else if (vt == "decimal") {
items = decimals;
formatString = "n0";
valueType = typeof(decimal);
}
else if (vt == "date") {
items = dates;
valueType = typeof(DateTime);
}
else if (vt == "enum") {
if (col == colComboDefault) {
items = enumsTable;
displayMember = "Display";
valueMember = "Value";
}
else
items = enums;
style = ComboBoxStyle.DropDownList;
valueType = typeof(DayOfWeek);
}
else if (vt == "person") {
items = persons;
valueType = typeof(Person);
}
if (col == colComboDefault) {
var cell2 = (DataGridViewComboBoxCell) dgv.Rows[rowIndex].Cells[colIndex];
cell2.DataSource = items;
cell2.ValueType = valueType;
cell2.DisplayMember = displayMember;
cell2.ValueMember = valueMember;
}
} catch (Exception ex) {
MessageBox.Show(dgv.FindForm(), ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
};
return dgv;
}
}
internal class Person {
public String name;
public override string ToString() {
return name;
}
public override bool Equals(object obj) {
if (obj is Person)
return String.Compare(name, ((Person) obj).name, false) == 0;
return false;
}
public override int GetHashCode() {
return name.GetHashCode();
}
}
Solution
Use the DataBindingComplete event handler to iterate through your rows and set the source for each DataGridViewComboBoxCell.
Example
Here's an example of how I did this. You'll need to add a DataGridView and a ComboBox (with two options, i.e. "option 1" and "option 2", for switching the DataGridView.DataSource) to your Form.
Public Class Form1
Public Property Groups As List(Of Group)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Groups = Me.InitializeGroups()
Dim cbc As New DataGridViewComboBoxColumn()
cbc.DisplayMember = "Name"
cbc.ValueMember = "ID"
cbc.HeaderText = "Matches"
cbc.Name = "Match"
cbc.Width = 150
Me.DataGridView1.Columns.Add(cbc)
Me.ComboBox1.SelectedIndex = 0
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim examples As New List(Of Example)()
If Me.ComboBox1.SelectedIndex = 0 Then
examples.Add(New Example("Me", "blah"))
examples.Add(New Example("You", "blah"))
Else
examples.Add(New Example("Him", "blah"))
examples.Add(New Example("Her", "blah"))
examples.Add(New Example("It", "blah"))
End If
Me.DataGridView1.DataSource = examples
End Sub
Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
For Each row As DataGridViewRow In Me.DataGridView1.Rows
Dim cell As DataGridViewComboBoxCell = TryCast(row.Cells("Match"), DataGridViewComboBoxCell)
cell.DataSource = Me.Groups.Where(Function(g) g.Members.Contains(row.Cells("Foo").Value.ToString())).ToList()
cell.Value = cell.Items(0).ID ' Same property as combocell.ValueMember
Next
End Sub
Private Function InitializeGroups() As List(Of Group)
Dim groups = New List(Of Group)() From { _
New Group() With { _
.ID = 1, _
.Name = "All", _
.Members = New List(Of String)() From { _
"Me", _
"You", _
"Him", _
"Her", _
"It" _
} _
}, _
New Group() With { _
.ID = 2, _
.Name = "Them", _
.Members = New List(Of String)() From { _
"Him", _
"Her", _
"It" _
} _
}, _
New Group() With { _
.ID = 3, _
.Name = "Us", _
.Members = New List(Of String)() From { _
"Me", _
"You" _
} _
}, _
New Group() With { _
.ID = 4, _
.Name = "Me", _
.Members = New List(Of String)() From { _
"Me" _
} _
}, _
New Group() With { _
.ID = 5, _
.Name = "Human", _
.Members = New List(Of String)() From { _
"Me", _
"You", _
"Him", _
"Her" _
} _
}, _
New Group() With { _
.ID = 6, _
.Name = "Non-human", _
.Members = New List(Of String)() From { _
"It" _
} _
} _
}
Return groups
End Function
End Class
Public Class Example
Public Sub New(foo__1 As String, bar__2 As String)
Foo = foo__1
Bar = bar__2
End Sub
Public Property Foo() As String
Get
Return m_Foo
End Get
Set(value As String)
m_Foo = Value
End Set
End Property
Private m_Foo As String
Public Property Bar() As String
Get
Return m_Bar
End Get
Set(value As String)
m_Bar = Value
End Set
End Property
Private m_Bar As String
End Class
Public Class Group
Public Sub New()
Me.Members = New List(Of String)()
End Sub
Public Property ID() As Integer
Get
Return m_Id
End Get
Set(value As Integer)
m_Id = value
End Set
End Property
Private m_Id As String
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = Value
End Set
End Property
Private m_Name As String
Public Property Members() As List(Of String)
Get
Return m_Members
End Get
Set(value As List(Of String))
m_Members = Value
End Set
End Property
Private m_Members As List(Of String)
End Class
I have a VB.net form and I'm trying to bind some data to controls.
I'm using the following code:
Private Sub InitDataLayer()
'Create table
DataTable = New DataTable
DataTable.Columns.Add("ID")
DataTable.Columns("ID").DataType = GetType(Integer)
DataTable.Columns("ID").AllowDBNull = False
DataTable.Columns.Add("Name")
DataTable.Columns("Name").DataType = GetType(String)
DataTable.Columns("Name").AllowDBNull = False
'Create new rows
'1st Row
Dim NewRow As DataRow = DataTable.NewRow
NewRow.Item("ID") = 1
NewRow.Item("Name") = "John"
DataTable.Rows.Add(NewRow)
'2nd Row
NewRow = DataTable.NewRow
NewRow.Item("ID") = 2
NewRow.Item("Name") = "Steve"
DataTable.Rows.Add(NewRow)
'Bind controls
'Textboxes
TextBoxID.DataBindings.Add(New Binding("text", DataTable, "ID"))
TextBoxName.DataBindings.Add(New Binding("text", DataTable, "Name"))
'Navigator
Dim BS As New BindingSource
BS.DataSource = DataTable
BindingNavigator1.BindingSource = BS
End Sub
The code works but when I move to the second row in the binding navigator, the controls don't update (see Video)
What is missing to the code please ?
Thanks
Solution:
Private Sub InitDataLayer()
'Create table
DataTable = New DataTable
DataTable.Columns.Add("ID")
DataTable.Columns("ID").DataType = GetType(Integer)
DataTable.Columns("ID").AllowDBNull = False
DataTable.Columns.Add("Name")
DataTable.Columns("Name").DataType = GetType(String)
DataTable.Columns("Name").AllowDBNull = False
'Create new rows
Dim NewRow As DataRow = DataTable.NewRow
NewRow.Item("ID") = 1
NewRow.Item("Name") = "John"
DataTable.Rows.Add(NewRow)
NewRow = DataTable.NewRow
NewRow.Item("ID") = 2
NewRow.Item("Name") = "Steve"
DataTable.Rows.Add(NewRow)
'Bind controls
Dim BS As New BindingSource
BS.DataSource = DataTable
TextBoxID.DataBindings.Add(New Binding("text", BS, "ID"))
TextBoxName.DataBindings.Add(New Binding("text", BS, "Name"))
BindingNavigator1.BindingSource = BS
End Sub
I need to query an array. I have tried to use LINQ but with no success.
Here is a simplified structure of Insurance
Public Class Insurance
Public _typ As String
Public _numb As Number()
Public _indi As Indicator()
End Class
Public Class Number
Sub New(ByVal n As String, ByVal i As String)
Me._ntype = n
Me._value = i
End Sub
Public _ntype As String
Public _value As String
End Class
Public Class Indicator
Sub New(ByVal it As String, ByVal ind As String)
Me._itype = it
Me._ind = ind
End Sub
Public _itype As String
Public _ind As String
End Class
Here I have construct a little example to explain how the array of Insurance looks. In real there is a Service who delivers the array to me.
Dim insarray(4) As Insurance
Dim insa As New Insurance
insa._typ = "SJUKVARD"
insa._indi = New Indicator() {New Indicator("ST", "G"), New Indicator("TAX", "P"), New Indicator("PT", "6")}
insa._numb = New Number() {New Number("PIN", "1000"), New Number("AGN", "A0001")}
insarray(0) = insa
Dim insa2 As New Insurance
insa2._typ = "SJUKVARD"
insa2._indi = New Indicator() {New Indicator("ST", "G"), New Indicator("TAX", "P")}
insa2._numb = New Number() {New Number("PIN", "2000"), New Number("AGN", "A0002")}
insarray(1) = insa2
Dim insa3 As New Insurance
insa3._typ = "SJUKVARD"
insa3._indi = New Indicator() {New Indicator("ST", "G"), New Indicator("KAL", "T")}
insa3._numb = New Number() {New Number("PIN", "3000"), New Number("AGN", "A0003")}
insarray(2) = insa3
Dim insa4 As New Insurance
insa4._typ = "SJUKVARD"
insa4._indi = New Indicator() {New Indicator("ST", "G"), New Indicator("TAX", "P")}
insa4._numb = New Number() {New Number("PIN", "4000")}
insarray(3) = insa4
Dim insa5 As New Insurance
insa5._typ = "SJUK"
insa5._indi = New Indicator() {New Indicator("ST", "F"), New Indicator("TAX", "P")}
insa5._numb = New Number() {New Number("PIN", "5000"), New Number("AGN", "A0005")}
insarray(4) = insa5
Dim myIns As IEnumerable(Of Object)
myIns = ...(here should to LINQ question be)
In "myIns= ..." I want to construct a LINQ query which
look for Insurances in the array which have _typ="SJUKVARD"
and in the Insurance _numb array if some of the Number objects has
_ntype="AGN"
and in the Insurance _indi array if some of the Indicator objects has
_itype="TAX"
and in the Insurance _indi array if some of the Indicator objects has
_itype="ST" AND _ind="G"
and in the Insurance _indi array NOT has a Indicator objects with
_type="PT
So the only hit will be Insurance "insa2". Is this possible with LINQ?
Hope someone can help me :)
myIns = insarray.Where(Function(i) i._typ = "SJUKVARD" AndAlso _
i._numb.Any(Function (n) n._ntype = "AGN") AndAlso _
i._indi.All(function(ind) (ind._itype <> "PT") AndAlso _
(ind._itype = "TAX" OrElse ( ind._itype = "ST" AndAlso ind._ind="G"))))