Passing data to DataGridView - vb.net

How can I pass data from my textboxes (in form1) to my DataGridView (in form2)?
here is the code i used.
DataGridView1.ColumnCount = 2
DataGridView1.Columns(0).Name = "Customer"
DataGridView1.Columns(1).Name = "Information"
Dim FNAME As String = Form1.TBFNAME.Text.ToString
Dim row As String() = New String() {"FULLNAME", FNAME}
DataGridView1.Rows.Add(row)
row = New String() {"EMAIL", Form1.TBEADD.Text}
DataGridView1.Rows.Add(row)
row = New String() {"ADDRESS", Form1.TBADDRESS.Text}
DataGridView1.Rows.Add(row)
row = New String() {"CONTACT NO.", Form1.TBCONTACT.Text}
the dgv have two columns. and the passed data will appear to the 2nd column but whenever i already input the data it's still blank in the dgv

Your code is missing
DataGridView1.Rows.Add(row)
for the "CONTACT NO" row.
Other than that, it seems fine. Are FNAME,TBEADD,TBADDRESS, and TBCONTACT all standard textboxes? Where is this code called from?
Some troubleshooting suggestions:
Try creating a minimal project with 4 textboxes, a DataGridView, and a button. Put your code above into the Click event of the button. Then try it with the DataGridView and button on a second form. Compare that to your existing project.

Related

In VB.NET I am having problems populating a DataGridView combobox using a datatable

I have a datatable (dsBrands) that I want to display in a datagridview. The combobox in the datagridview gets its selections from a different table(dsGroups). How do I show in the combobox the value that is currently stored in the dsBrands table? Below is my code that works except that the combobox is left blank. The combobox collection does populate correctly from dsGroups. The value that needs to be displayed in the combobox from dsBrands is in the collection. The --> is just to make the line stand out and not in the actual code.
Private Sub FillBrands()
Dim TransCount As Integer
Dim Group As String
If Not ds.Tables.Contains("dsBrands") Then Else ds.Tables("dsBrands").Clear()
conn.Open()
daBrands = New OleDbDataAdapter("Select * from Brands", conn)
daBrands.FillSchema(ds.Tables("dsBrands"), SchemaType.Source)
daBrands.Fill(ds, "dsBrands")
conn.Close()
dgv1.AutoGenerateColumns = False
bs1.DataSource = ds.Tables("dsBrands")
dgv1.DataSource = bs1
Dim colDisplay As New DataGridViewCheckBoxColumn
colDisplay.DataPropertyName = "Display"
colDisplay.HeaderText = "Include?"
colDisplay.Name = "Display"
colDisplay.Visible = True
Dim colGroupList As New DataGridViewComboBoxColumn
colGroupList.HeaderText = "Add to Group"
colGroupList.Name = "GroupList"
colGroupList.Visible = True
colGroupList.DataSource = ds.Tables("dsGroups")
--> colGroupList.DataPropertyName = "BGroup" 'BGroup is a field in dsBrands table.
dgv1.Columns.Add(colDisplay)
dgv1.Columns.Add(colBrand)
dgv1.Columns.Add(colGroup)
dgv1.Columns.Add(colGroupList)
End Sub
Just as when binding a regular ComboBox, you need to set the DisplayMember and ValueMember properties of your column. The DisplayMember specifies the column whose values get displayed and the ValueMember specifies the column whose values correspond to the grid data. ValueMember should specify the PK column of the table bound to the column that corresponds to the FK column of the table bound to the grid.

Filling ComboBox Column in DatagridView VB.Net

i have a datagridview with 2 columns as combobox and i want to fill the second one depending on the first one.
Ex. I have a table in my database with stations
TableStations
Station 1
Station 2
And each stations has a different amount of outputs
Ex.
Station 1 Station 2
OutP1 OutP5
OutP2 OutP6
OutP7
What i want to do in the datagridview is that when the user selects from the first combobox a station the next combobox gets filled with the outputs for that station, my problem comes when the user adds a second row in the datagridview if he selects a diferent station the info in the first row will be modified.
Is there any solution for this or any other way to do what i want?
Thanks in advance
EDIT: this is the code im using
Con.Open()
cmd.Parameters.Clear()
With cmd
.CommandText = "Select output From List_outputs where station=#station"
.Parameters.AddWithValue("#station", datagridview1.Item(0, e.RowIndex).Value)
.Connection = Con
reader = .ExecuteReader
End With
combobox2.Items.Clear()
While reader.Read
combobox2.Items.Add(reader("output "))
End While
reader.Close()
This code is under the cellclick event of my datagridview.
This is a bit tricky since you can't set the column's data source. Setting the column's data source affects the entire column. You must set the data source of each cell separately. I'll show you how to do it.
First add a DataGridView in an empty form. Don't add the columns, we're going to add the columns by code. You don't have to add the columns by code in your real project, but please follow what I did in this example. I add comments to make the code easy to understand. I choose to create two classes to hold Station and Output. This is also optional, you can just use a DataReader and add them manually. Hope this helps you.
Public Class Form1
Dim outputs As List(Of Output) ' this holds the fake output data.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Replace this section with the code to retrieve stations from database.
Dim stations As New List(Of Station) From {
New Station() With {.StationName = "Station 1"},
New Station() With {.StationName = "Station 2"}
}
' Add stations to first combobox
Dim firstColumn = New DataGridViewComboBoxColumn()
For Each station In stations
firstColumn.Items.Add(station.StationName)
Next
' Populate fake data, replace this section with the code to retrive outputs from database.
outputs = New List(Of Output) From {
New Output() With {.OutputName = "OutP1", .StationName = "Station 1"},
New Output() With {.OutputName = "OutP2", .StationName = "Station 1"},
New Output() With {.OutputName = "OutP5", .StationName = "Station 2"},
New Output() With {.OutputName = "OutP6", .StationName = "Station 2"},
New Output() With {.OutputName = "OutP7", .StationName = "Station 2"}
}
' add combobox columns to datagridview
DataGridView1.Columns.Add(firstColumn)
DataGridView1.Columns.Add(New DataGridViewComboBoxColumn())
End Sub
Private Sub DataGridView1_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
' Only process if the column is the second combobox.
' You will need to change the index according to your second combobox index.
' e.ColumnIndex = 1 because the second combobox index is 1 in this sample.
If e.ColumnIndex = 1 Then
' Filter the outputs by selected Station in the row.
' Change the ColumnIndex to your first combobox index.
' DataGridView1(0, e.RowIndex) because the first combobox index is 0 in this sample.
Dim outputByStation = outputs.Where(Function(x) x.StationName = DataGridView1(0, e.RowIndex).Value.ToString())
' Get current cell, we're going to populate the combobox
Dim currentCell = CType(DataGridView1(e.ColumnIndex, e.RowIndex), DataGridViewComboBoxCell)
' Populate the cell's combobox.
currentCell.Items.Clear()
For Each output In outputByStation
currentCell.Items.Add(output.OutputName)
Next
End If
End Sub
End Class
Public Class Station
Public Property StationName As String
End Class
Public Class Output
Public Property OutputName() As String
Public Property StationName() As String
End Class
Screenshot:

Change data according to selected item in combobox

I call into a function which runs a query into SQLServer and returns a DataTable with multiple columns. I want the data from the DataTable to change rows according to the selected item in the combobox.
Dim dt As New DataTable
Dim rInt As New Int32
dt = subGetDB()
rInt = ComboBox1.SelectedIndex
Textbox1.Text = dt.Rows(rInt)("description").ToString()
TextBox2.Text = dt.Rows(rInt)("accountFilter").ToString()
Am I on the right track with this so far?
Yes ... but you need to put all of the code above into the SelectedValueChanged event for the ComboBox1 object.

vb.net working with multiple controls added at runtime

I am adding a tab page and datagridview to a Tab Control for every record in a datatable.
I would like to have a new Tab/DataGridView for each record (there will be ~3 for right now). I am declaring a new DataGridView D. How do I refer to these controls later?
I will want to do things like save changes in the datagridview to the database. Currently I can get the data on the screen and it looks good, but I believe I am not adding the DataGridView controls correctly because I keep re-using "D" as the control.
Dim dt As New DataTable
GetDataTable("SELECT * FROM aFeeTypes DescSeq", dt)
Dim i As Integer
'for each class in the datatable add a tab and a datagridview
For i = 0 To dt.Rows.Count - 1
Dim dr As DataRow
dr = dt.Rows(i)
Dim D = New DataGridView
D.Visible = True
Dim tp As New TabPage
tp.Name = "tp" & i
tp.Text = dr.Item("Desc2")
frmUI.tcFee.TabPages.Add(tp)
frmUI.tcFee.TabPages(i).Controls.Add(D)
dgv_Fill(D, "SELECT * FROM Fee WHERE ClassID=" & dr.Item("ClassID") & " ORDER BY Seq")
D.AutoResizeColumns()
D.Width = tp.Width
D.Height = tp.Height
Next i
this does not work:
With frmUI.Controls("D" & i)
.AutoResizeColumns()
.Width = tp.Width
.Height = tp.Height
End With
D is purely the variable name in the scope you are using it in.
You need to give the control a unique Name that yo can reference it by later.
The Name property can be used at run time to evaluate the object by
name rather than type and programmatic name. Because the Name property
returns a String type, it can be evaluated in case-style logic
statements (Select statement in Visual Basic, switch statement in
Visual C# and Visual C++).
I found a solution to the problem. The problem is that the new row has an autonumber ID.
When da.update(dt) occurs, the new row is inserted to the database. The database knows the new autonumber ID. However, the datatable does not.
For the datatable to know, the dataadapter is refilled. However, this causes the datatable to have all the old rows plus all the new rows and they all appear in the datagridview.
By clearing the old rows from the datatable, the fill refreshes all the data in the datatable and therefore refreshes the datagridview.
Public Sub dgv_AddRow(ByVal dgvName As String)
Dim dgv As DataGridView = colDataGridView.Item(dgvName)
Dim da As SqlDataAdapter = colDataAdapter.Item(dgvName)
Dim dr As DataRow = frmUI.allDataSet.Tables(dgvName).NewRow
'autopopulate the class id
dr("ClassID") = dgv.Parent.Tag
'add the new row
frmUI.allDataSet.Tables(dgvName).Rows.Add(dr)
'get the changed table
Dim dt As DataTable = frmUI.allDataSet.Tables(dgvName)
'inserts the new row to the database. concurrency violation
'will occur because datatable does not know the new Autonumber ID for the new row.
da.Update(dt)
'remove the datatable rows so they can be replaced using the adapter fill
'if rows are not cleared, following fill causes datatable to
'have existing rows plus all the rows again due to the fill
frmUI.allDataSet.Tables(dgvName).Rows.Clear()
'refill the adapter (refill the table)
'Everything you do to the underlying dataTable
'gets displayed instantly on the datagridview
da.Fill(frmUI.allDataSet, dgvName)
End Sub

Datagridview has wrong number of columns when binding to a table

I need to have multiple lines in a cell, so I use DataGridViewTextBoxColumn.DefaultCellStyle.WrapMode =DataGridViewTriState.True.
I add columns (datagridviewtextboxcolumn) in designer. Then bound datagridview to a table which has exact the same columns as datagridview. Then I find that datagridview has duplicate columns: the first column is empty (which I guess is added through designer), the second column is filled with data from table. My question is how to correctly allow multi-lines and bound to a table at the same time?
In Designer
Friend WithEvents DGV As New System.Windows.Forms.DataGridView
Friend WithEvents columnClient As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents columnAccount As System.Windows.Forms.DataGridViewTextBoxColumn
Me.DGV.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.columnClient, Me.columnAccount})
Dim cellStyle As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle
cellStyle.WrapMode = DataGridViewTriState.True
Me.columnClient.DefaultCellStyle = cellStyle
Me.columnAccount.DefaultCellStyle = cellStyle
Then I bound datagridview to a table
DGV.DataSource = m_table
m_table.Columns.Add(columnClient)
m_table.Columns.Add(columnAccount)
Dim rowText As DataRow = m_table.NewRow
Dim strBaseKey As String="base key"
Dim accountkey As String="account key"
rowText(columnClient) = strBaseKey
rowText(columnAccount) = accountKey
Add: I just deleted columns in designer and it works now.
The solution is simple: just do not add columns to datagridview in designer; instead add columns to table and then bound datagridview to table. To enable multi-lines in datagridview, set the column.DefaultCellStyle.WrapMode=DataGridViewTriState.True
DGV.DataSource = m_table
m_table.Columns.Add(columnClient)
m_table.Columns.Add(columnText)
Dim rowText As DataRow = m_table.NewRow
rowText(columnClient) = "Bob"
rowText(columnAccount) ="Account1" & Encironment.Newline & "Account 2"
DGVTable.Columns(columnText).DefaultCellStyle.WrapMode = DataGridViewTriState.True
The datagridview will show:
columnClient columnAccount
Bob Account1
Account2