Question Adding data to a DataGrid

BleepyEvans

Active member
Joined
May 2, 2011
Messages
41
Programming Experience
1-3
Hey guys, just a simple question, for someone whos never used DataGrids before

How can I add preset data to be displayed in a datagrid when a button is pressed.

For example
There are 2 collumns, 1. Number and 1 Letter. When I press a button 1 is added under collumn Number, and A is added to collumn Letter.
When the button is pressed again a new row is added, with 2 under Number and B under Letter.

Thanks in advance
 
Last edited:
Sorry, I'm using Visual Studio 2010 and I can't remember which one it is.

I basically just want a table, and I couldn't find any other tool other than the datagrid or datagridview.
 
If I can't remember, I usually open my project and take a look. If you're using VB 2010 then it is most likely the DataGridView because that's the only one in the Toolbox by default. It's important because they are two different controls and work differently. A solution for one will likely not work for the other.

Anyway, one solution is to just call Rows.Add on your grid and pass the cell values as arguments.
 
Ive figured out how to add new rows
VB.NET:
Dim dgvRow As New DataGridViewRow
        Dim dgvCell As DataGridViewCell

        dgvCell = New DataGridViewTextBoxCell()
        dgvCell.Value = "1"
        dgvRow.Cells.Add(dgvCell)

        dgvCell = New DataGridViewTextBoxCell()
        dgvCell.Value = "A"
        dgvRow.Cells.Add(dgvCell)

        DataGridView1.Rows.Add(dgvRow)

Any ideas on how to increase the 1 for each new row?
 
Last edited:
You don't have to create each cell like that. As I said, just call Rows.Add and pass the values:
VB.NET:
DataGridView1.Rows.Add(1, "A")
Note that there are no double quotes on the number because it's supposed to be a number, not a String.

As for incrementing the number, store it in a variable and increment that variable each time. Obviously it can't be a local variable because it needs to persist the value between method calls.
 
Wow thats alot simpler lol. I guess this is the problem with following tutorials aimlessly.

Solved Thanks :)
 
Last edited:
There's often multiple ways to skin a cat. Tutorials will often not show the simplest way because the simplest way can often be less flexible. Sometimes though, the tutorial just isn't that great and makes things more complicated for no apparent reason. I would never create a row and add cells, except if I wanted cells different to those prescribed by the grid columns, because the grid itself can always create the row for you with the cells already included.
 
Back
Top