I have a function which return a list of countries as data table. How do I add these row values to a combo box?
For Each row as DataRow in fooDataTable.Rows
combobox.Items.add(row)
Next
Some how this does not fill up the values on my combo box. The datatable returns 100 rows. Each row has 2 columns. I am trying to add all the 100 datarows with the first column. Any help would be greatly appreciated.
A DataRow is an object and while objects can be added to a Combo or ListBox, in this case the result is not very useful. When you store an Object in .Items, the result of the .ToString function is what displays. In this case it will just display System.Data.Datarow
The best solution is what LarsTech suggested and use the existing datatable as the datasource. This is economical because there is nothing new created for the CBO:
ComboBox.DataSource = fooDataTable
ComboBox.DisplayMember = "column name in DT"
Another way is to modify your loop:
combobox.Items.Add(row("col name").ToString)
This adds the data from the column name to the cbo. If this was something like peoples names and you wanted to show First and Last name:
combobox.Items.Add(String.Format("{0}, {1}", row("LastName").ToString,
row("FirstName").ToString))
This is similar except we are formatting the contents of both columns as we add it to the CBO.
Still another way is to create a class object for each row which returns what you want to display via the ToString override; and add them to the CBO, but that is overkill in this case, given the economy of the first alternative.
Related
I have set a combobox to be visible in column1 of my Datagridview. Now I'm trying to fill same row of Datagridview where Combobox appears, from Combobox_Key_Down event. This is my code for showing combobox:
Private Sub My_DGV_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles MY_DGV.CellMouseClick
If e.RowIndex >= 0 Then
With My_DGV
If .Columns(.Rows(e.RowIndex).Cells(e.ColumnIndex).ColumnIndex).Name = "Column1" Then
.CurrentCell = .Rows(.CurrentRow.Index).Cells(.CurrentCell.ColumnIndex)
Show_Combobox(.CurrentRow.Index, .CurrentCell.ColumnIndex) 'function that shows my Combobox in that cells
Combo.Visible = True
Else
Combo.Visible = False
End If
End With
End If
End Sub
I tried many things, but I don't know how to determine in which row Combobox appears and how give that Datagridview row my Combobox values. Someone please give me a clue of what should I do. Thanks in advance !
The first problem with your approach is that the DGV can have only one DataSource: it can either show the m:m association table or the related elements. If you include columns from one of the tables into the query for display, the table becomes non updatable and users can be confused why they cannot edit something they can see. It seems of little value they way you describe it, since they cannot see the detail data until after they make a selection.
Next, it requires another datatable to supply the details for CboColB. Since you want the DGV bound to a DataTable easy updates, you end up having to poke data into cells over and over.
Finally, consider what the user is confronted with. Using a Country table (200+ countries/locales with ISO code and name) and a list of flag colors, a table for CountryFlagColors will have hundreds and hundreds of rows (at just 2 colors per flag).
A better display might be to filter the m:m table (flagcolor) to a selected item so the user is only confronted with the data subset they are currently interested in:
The datatable used in the DGV is built from the m:m table:
The Country column is hidden.
When they choose from the CBO at the top, that is used as a RowFilter to limit the rows to the relevant ones.
In the RowValidating event, when the country cell is DBNull, copy the SelectedValue from the country combo to the DGV cell to fill in the blank
I would probably really make the user click a button and manually add a row so I could seed the country value then rather than depend on events.
It uses a DataAdapter and after adding X number of flag definitions, da.Update(dtFlagColors) applies/saves all the changes.
Ok, so that provides the core functionality to assign N color selections to define the flag colors for a country. The missing element is the 'details' for the Color item.
I added a meaningless int and string item to the Color table, one way to display these would be to create an alias in the SQL with the important details. Displaying them as discrete elements can either make the query non updatable or invites the user to edit things they cannot edit here. My silly SQL:
"SELECT Id, Name, Concat(Name , ' (' , intItem , ' ' , stritem,')') As Info from FColor"
Then use 'Info' as the display member on the CBO column in the dgv:
dc = DirectCast(dgvCF.Columns(0), DataGridViewComboBoxColumn)
dc.DataSource = dtFlagColors
dc.DisplayMember = "info"
dc.ValueMember = "id"
dgvCF.DataSource = dtSample
The combo column has its own datasource of course, in order to display one thing and use another for as the Value to give back to you. Result (the values are silly):
It is not exactly what you want, but comes close and is much simpler. It also requires almost no code for driving the associative entity. Another alternative would be to use a DGV as the second picker so you can show the extended data and manually add rows to a DGV:
If you set the dropdown style to Nothing, it looks like a text column.
I have around 15 comboboxes on my form, all being loaded with the same information pulled from a table(~150 entries). Currently I am taking the information from the table, then looping through the entries and adding them to each textbox. I'm wondering if there's a more efficient way to load these comboboxes then having to individually add the table entry into each combobox, having to list 15 lines of code within the For loop.
I'm not seeing any performance issues with this, but figured I might as well work with the most efficient way possible rather than stick with what works. :)
You can create a list of the combo boxes, and then just loop through them. For instance:
Dim cbos() As ComboBox = {ComboBox1, ComboBox2, ComboBox3}
For Each cbo As ComboBox In cbos
' Load cbo from table
Next
Alternatively, if they are named consistently, you could find the combo box by name:
For i As Integer = 1 to 15
Dim cbo As ComboBox = DirectCast(Controls("ComboBox" & i.ToString())), ComboBox)
' Load cbo from table
Next
Since Combobox items are a collection, if their elements are the same, you can build and array with the objects you want to insert, and then just insert this array to each ComboBox with the method AddRange() (it's a method which exists inside the Combobox.items).
Getting an example from MSDN:
Dim installs() As String = New String() {"Typical", "Compact", "Custom"}
ComboBox1.Items.AddRange(installs)
Then you would only have to do a loop to add the array to each ComboBox. Of course, you will need to build your array first on your own, instead of this easy string array from the example.
Reference:
MSDN - AddRange
You could also do it this way since you mentioned that you already have a table.
Use a datatable
Change your table object into a datatable, which will assist in binding to the comboboxes. It might help if you add the datatable to a dataset too. That way you can attach all ComboBoxes (which are UI elements that let users see information) to the same DataSource, which is the datatable, in the dataset.
Binding
Now all you need to do is loop through all the comboboxes and set the datasource to the same table, that is if you decide to do it programmatically like so:
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "au_id"
ComboBox1.DisplayMember = "au_lname"
A further tutorial on this with the example above is found here
You can then also get the user selected value with ComboBox1.selectedValue.
On the other hand, if you did this with C# WPF, you can bind each comboBox in the XAML directly, I am unsure if this can be done in VB.net as I tried to look for the option but did not manage to do so, something you might want to try though.
Some very useful tutorials and guides on Data binding, which you might be interested:
~ denotes recommended reading for your question
MSDN: Connect data to objects
DotNetPerls on DataGridView (note this isn't a combobox, just displaying values)
~ VBNet DataTable Usage from DotNetPerls (this is in relation to 1.)
~ SO Q&A on Binding a comboBox to a datasource
Concepts of Databinding
I'm using VB.NET to make a stand-alone executable containing an unbounded DataGridView.
One of its columns is a combobox. I add rows to the combobox with some simple code
like this:
For r As Int16 = 0 To eachLine.GetUpperBound(0)
Dim dgvcbc As DataGridViewComboBoxColumn = grd.Columns(col)
' Errors: dgvcbc.Items.Clear()
dgvcbc.Items.Add(eachLine(r))
Next r
Works great the first time, but when I try to clear it, in order to add some different
items in the combobox, I get this error 100s of times:
> DataGridViewComboBoxCell value is not valid
Any ideas on how to fix this and why it occurs?
The issue is that, if you clear the Items in that column, every cell in that column becomes invalid. Every value in that column has to match one of the items in the drop-down list and, if there's no items, no value can be valid. It doesn't make sense to clear the drop-down list. You must leave at least the items that match the values in the cells of that column.
I have a main DataSet which contains several DataTables. These different DataTables are bound to their DataGridView's DataSource respectively.
My problem is whenever I modify something in the display area such as the description textbox below and then click on save....
<<< To >>>
The DataGridView doesn't have the replicated changes, as seen here:
I need a way to update the DataTable ... My save button successfully saves the information. I am quite new to DataSets and DataTables so this is my first time trying to update a DataTable. I doubt I need to reload the information in the DataTable, there must be something more efficient?
Updating a DataTable With Unknown Indexes
For more information: How to: Edit Rows in a DataTable
In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.
Update existing records in typed datasets (Row index not known)
Assign a specific DataRow to a variable using the generated FindBy method, and then use that variable to access the columns you want to edit and assign new values to them.
Dim Description As String = "Hello World Modified"
'Update DataTable
Dim Row As DataSet1.DataTableRow
Row = DataSet1.DataTableRow.FindByPrimaryKey(PK)
Row.Description = Description
Update existing records in untyped datasets (Row index not known)
Use the Select method of the DataTable to locate a specific row and assign new values to the desired columns
Dim Description As String = "Hello World Modified"
'Update DataTable
Dim Row() As Data.DataRow
Row = DataSet1.Tables("Table1").Select("PrimaryKey = '10'")
Row(0)("Description") = Description
Once this is done, I don't need to refresh anything else - my DataGridView has the latest information.
How do I add new record to DataGridView control in VB.Net?
I don't use dataset or database binding. I have a small form with 3 fields and when the user clicks OK they should be added to the DataGridView control as a new row.
If you want to add the row to the end of the grid use the Add() method of the Rows collection...
DataGridView1.Rows.Add(New String(){Value1, Value2, Value3})
If you want to insert the row at a partiular position use the Insert() method of the Rows collection (as GWLlosa also said)...
DataGridView1.Rows.Insert(rowPosition, New String(){value1, value2, value3})
I know you mentioned you weren't doing databinding, but if you defined a strongly-typed dataset with a single datatable in your project, you could use that and get some nice strongly typed methods to do this stuff rather than rely on the grid methods...
DataSet1.DataTable.AddRow(1, "John Doe", true)
I think you should build a dataset/datatable in code and bind the grid to that.
The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:
myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});
or something to that effect.
When I try to cast data source from datagridview that used bindingsource it error accor cannot casting:
----------Solution------------
'I changed casting from bindingsource that bind with datagridview
'Code here
Dim dtdata As New DataTable()
dtdata = CType(bndsData.DataSource, DataTable)
If you want to use something that is more descriptive than a dumb array without resorting to using a DataSet then the following might prove useful. It still isn't strongly-typed, but at least it is checked by the compiler and will handle being refactored quite well.
Dim previousAllowUserToAddRows = dgvHistoricalInfo.AllowUserToAddRows
dgvHistoricalInfo.AllowUserToAddRows = True
Dim newTimeRecord As DataGridViewRow = dgvHistoricalInfo.Rows(dgvHistoricalInfo.NewRowIndex).Clone
With record
newTimeRecord.Cells(dgvcDate.Index).Value = .Date
newTimeRecord.Cells(dgvcHours.Index).Value = .Hours
newTimeRecord.Cells(dgvcRemarks.Index).Value = .Remarks
End With
dgvHistoricalInfo.Rows.Add(newTimeRecord)
dgvHistoricalInfo.AllowUserToAddRows = previousAllowUserToAddRows
It is worth noting that the user must have AllowUserToAddRows permission or this won't work. That is why I store the existing value, set it to true, do my work, and then reset it to how it was.
If your DataGridView is bound to a DataSet, you can not just add a new row in your DataGridView display. It will now work properly.
Instead you should add the new row in the DataSet with this code:
BindingSource[Name].AddNew()
This code will also automatically add a new row in your DataGridView display.