How can I change the column name from datagridview with access database - vb.net

or how can I populate the rows only from my datagridview since I want to assign a columnheader name on my datagridview instead of filling the database with all my data. I want to adjust the column height/width and such of each column. Thank you

I know why you put an image, but you should perhaps try to avoid it for future questions; people tend to prefer seeing code as text they can copypaste
You have your DGV set to autogenerate columns so it makes columns with a HeaderText that is the same name as the column. Just change the column HeaderText after the columns have been bound (binding happens when you set the DataSource property):
For example you can look the DGV column up by the datatable column it is bound to:
yourDataGridView.Columns.Cast(Of DataGridViewColumn)().First(Function(c) c.DataPropertyName = "ip").HeaderText = "IP"
Bound columns don't have a name, only an index position, so if you want to find them by name you'll have to look through the columncollection searching for eg where the column's DataPropertyName is "ip", which is what the LINQ above does. It's a bit awkward as a syntax because a DataGridViewColumnCollection doesn't do LINQ without being cast. It might be simpler to put all your mappings into a dictionary and use a loop:
Dim d = New Dictionary(Of String, String) From
{{"ip", "IP"}, {"aws", "AmazonWebServices"}, ... }
For Each dgvc as DataGridViewColumn in d
If d.ContainsKey dgvc.DataPropertyName Then d.HeaderText = d(dgvc.DataPropertyName)
Next dgvc
If you know "ip" column will always be first you can more simply:
yourDataGridView.Columns(0).HeaderText = "IP"

Related

DataGridViewComboboxCell display member not showing up

Goal
A datagridview of SteelTypes has a column that has been bound to a dataview (SteelThicknesses). I can select the data and set it correctly. However I cannot load the same information. My datagridview comboboxcell contains the value and editted formatted text but I cannot set the display member information.
Current problem
I have all of my textbox columns loading correctly except the combobox column. The variable of cbCol is set correctly and the EditedFormattedValue and FormattedValue contain the value I want! However the displayMember does not get replicated into the datagridviewcombobox cell.
I am trying to display a "3" into the Épaisseur (thickness) column via setting its value to a primary key (PK_SteelThickness):
See the results below. Everything except my comboboxcell is populated:
Appreciate the help in advance, this has gotten me crazy :)
You don't set the text. You set the underlying ID. The idea is that you bind the column to a parent table and you bind the grid to a child table that has a foreign key to that parent table. You set the foreign key value in the grid cell and the corresponding text value from the parent table gets displayed.
As an example, let's say that you have a Handedness table like so:
Id Name
1 Right
2 Left
3 Ambidextrous
and you have a Person table like so:
Id Name HandednessId
1 Peter 2
2 Paul 1
3 Mary 3
In your grid you would create a DataGridViewComboBoxColumn and set its DataPropertyName property to "HandednessId". When you then bound your Person table to the grid, the HandednessId column would bind to the combo box column. You would bind your Handedness table to the column and set the DisplayMember and ValueMember to "Name" and "Id" respectively. The grid would then display "Left", "Right" and "Ambidextrous" for "Peter", "Paul" and "Mary" respectively. If you wanted to make Peter ambidextrous, you would set the HandednessId cell Value to 3 and then it would display "Ambidextrous".
See this for more information:
Adding a ComboBox Column to a DataGridView
It seems like you're making a lot of work for yourself here. Datagridcombobox can be used to decode a value simply by having its
DataSource set to something that provides the key/value lookup, for example a SteelThicknesses datatable with two columns Disp and Val and has rows like "Thick",1 "Medium", 2 "Thin", 3,
DisplayMember set to a string of the column name from the lookup table that contains the text to show, for example "Disp",
ValueMember set to the string column name from the lookup that has the value that relates to the text to show, for example "Val" and
DataPropertyName set to the name of the property(column) in the other table that has the value to be decoded (one of the values in the Val column of the lookup table) (for example a Products table with a SteelThicknessID column).
The datagridview is bound to the products datatable, the combo will find e.g. 3 in the steelthicknessid column, it will look 3 up in the Val column of the steelthicknesses table and show the text it finds in the Disp column of that row from steelthickesses.if the user changes the value shown by dropping the combo list and picking Thick, it will work the reverse and take 1 from the Val column and update the products table with the new value 1 for steelthicknessid. If you don't want that, make the column or datagridview read only
For a more involved discussion see my answer in DataGridView Loading From LINQ
This is an odd behavior but I found that changing my loading method calls from the new() to the form Load() made it work...
So I changed my initial code from this:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
LoadSteelPlates()
LoadPlateQuotes()
End Sub
To this:
Private Sub frmQuotePads_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadSteelPlates()
LoadPlateQuotes()
End Sub
This is the only code that was modified and now it works.

Filter DataGridView across all columns

Sorry for my bad English. I am an old German man, I want to filter a DGV across all columns. In the Moment I use following filter:
Dim Such_Spalte = Me.DtS_DGV.DTT_1.article_1Column.ColumnName
But I have 10 Columns (article_1 to Article_10)
If as an example Sugar is in column 1,3,5 I want to see all records where sugar occurs.
I hope this is understandable
You seem to be using strongly typed datasets and as such I would expect that your datagridview is bound through a BindingSource (the windows forms designer sets it up this way, and my presumption is that you used te designer to do your binding)
If your datagridview is indeed bound through a bindingsource:
Dim bs = DirectCast(datagridviewX.DataSource, BindingSource)
Dim sb = New StringBuilder() 'it will hold the filter string
For Each col in DtS_DGV.DTT_1.Columns
sb.AppendFormat("[{0}] = '{1}' OR ", col.ColumnName, "Sugar")
Next col
sb.Length -= 3 'remove the trailing OR
bs.Filter = sb.ToString()
If your datagridview is bound direvtly to the table, it will have attached to the table's DefaultView property, a DataView, which also has a Filter that works in the same way. If this is the case, do the same thing with the loop to build the filter string, and then:
DtS_DGV.DTT_1.DefaultView.Filter = sb.ToString()

Won't add a default custom row on combobox

been having an issue displaying an empty item as default selected item on a combobox. This combobox is a filter for my gridview and currently my datagridview displays all data based on the first item of the combobox but what i wanted is to have an empty first combobox item so that datagridview will pull all data from database. When i run the app it says
System.ArgumentException: 'Input string was not in a correct
format.Couldn't store <> in ailment_id Column. Expected type is
Int32.'
My code to populate combobox from database:
Private Sub populateComboAilment()
data_adapter = New MySqlDataAdapter("SELECT * FROM ailment", myconnection.open())
Dim data_table As New DataTable
data_adapter.Fill(data_table)
'assign default value
Dim row As datarow = data_table.NewRow()
row(0) = ""
data_table.Rows.InsertAt(row, 0)
comboAilment.DataSource = data_table
With comboAilment
.DisplayMember = "name"
.ValueMember = "ailment_id"
End With
myconnection.close()
End Sub
Update: All is working now when I changed combobox ValueMember to a
name since it's an id before. but when I select another item it
displays nothing on the gridview because my datagridview query doesn't
know the name, only id since it's a foreign key.
Any help would be greatly appreciated!
Ah, I just looked more carefully at the code and you're not actually assigning a String containing "<>" but rather an empty String. It doesn't really matter though. A String is a String and you can't put one where a number is required. You might be able to use a String that contained digits because that could be implicitly converted to a number but a empty String doesn't qualify.
If you want an empty field in a DataRow then you need to do what ADO.NET does to represent a database null, i.e. use DBNull.Value. That means an object of type DBNull, which is required because ADO.NET predates nullable value types. You can't just use Nothing because would work for reference types but not value types, e.g. if you assign Nothing to an Integer variable you are effectively setting it to zero.
In short, you need to change this:
Dim row As datarow = data_table.NewRow()
row(0) = DBNull.Value
row(1) = DBNull.Value
data_table.Rows.InsertAt(row, 0)
In the case of the name column, its data type is String so you could use an empty String there (preferably String.Empty rather than "" but either works) but null is more appropriate because it is actually no value, rather than a value containing no characters.

Add column to DataGridView (VB.NET)

I would like to add a new column in my project, but a weird thing happened...
My code
adapter.fill(datatable)
dgv.datasource = datatable
dgv.columns.add("test","testHeader")
The column index of test column should be the last index.
However, I found the column index is 0 and the original 0th index turns to 1
I am not sure what happened. Is there any factor could cause this problem?
property settings of datagridview is wrong?
Try This Code For Adding the Column
Dim col As New DataGridViewTextBoxColumn
col.DataPropertyName = "PropertyName"
col.HeaderText = "SomeText"
col.Name = "colWhateverName"
DataGridView1.Columns.Add(col)
It's simple , get the total column count first and then add the column at the end :
Dim col as New DataGridViewColumn
col.HeaderText = "abc"
dgv.Columns.Insert(dgv.ColumnCount, col)
If the above code doesn't help , try adding column to the IDataTable itself :
datatable.Columns.Add("Header text", GetType(System.String)).SetOrdinal(datatable.Columns.Count)
Your code
adapter.fill(datatable)
dgv.datasource = datatable
dgv.columns.add("test","testHeader")
seems to be working properly.
I guess you are re-filling the datagridview that's why the added column is in index 0.
try to add
dgv.DataSource = Nothing
you will notice that the added column "test","testHeader" will be in index 0.
setting again
dgv.datasource = datatable
will cause the added column to remain at index 0 while the datatable will be added to the succeeding columns.
There's a DataGridViewColumn.DisplayedIndex property to control order of visible columns.
Keep in mind that DataGridView tracks theese values and update them for other columns in your grid. Chaning some of them to 0 will update all other columns to highter values.
This works because we clone an existing column while you cannot append a column that does already exist in a table. this also has the benefit of cloning all the column settings applied to the existing columns.
Clone a existing column:
Dim Newtestcolumn As DataGridViewColumn = Existingcolumn.Clone
Adjust header text:
Newtestcolumn.HeaderText = "test"
Add column to datagridview:
DataGridView1.Columns.Add(test)
If you add columns that does not match the current drawing format you need to update the datagridview object by calling:
DataGridView1.Update()
If you want to write to a specific column or you dont know the column name
you use this to return the amount of columns and then point to column 0 for cloning fx.
Dim Index = DataGridView1.Columns.GetColumnCount(DataGridViewElementStates.None)
You specify the column index like this:
DataGridView1.Columns.Item(index)
going back to the first line we would then write
Dim Newtestcolumn As DataGridViewColumn = DataGridView1.Columns.Item(index).clone

Joining bounded datagridview columns to default column

I have created 4 datagridview columns in design mode, and I have bounded a datatable to datagridview's datasource, and its generates autocolumns (4 Columns)in gridview.
My doubt is If I create 4 datagrid columns in design mode, How can I place the values of bounded columns to default columns (created in design mode).
See the screenshot, first four columns are created in designmode, other 3 columns autogenerated, But here I dont know how can I correctly place the cells.
This is my first doubt, second is,
Is it possible to add a new row to the same datagridview (from 4 textbox values) ? if yes, How ?
I appreciate your help on this doubts
You need to bind predefined columns to the columns of the datasource.
Set DataPropertyName property of DataGridViewColumns to the name of the column in the datasource
Me.DataGridViewColumnOrderDetID.DataPropertyName = "ORDER_DET_ID"
Me.DataGridViewColumnOrderDetItem.DataPropertyName = "ORDER_DET_ITEM"
' etc.
This can be done in the designer too.
And set DataGridView.AutoGeneratedColumns = false.
Create and add new row to the datatable based on the values of textboxes
Dim newRow As DataRow = yourdatatable.NewRow()
With newRow
.SetField(Of Int32)("ORDER_DET_ID", Int32.Parse(Me.TextBoxOrderDetID.Text))
.SetField(Of String)("ORDER_DET_ITEM", Me.TextBoxOrderDetItem.Text)
' etc.
End If
yourdatatable.Rows.Addf(newRow)