Adding data to a grid //newbie question

  • Thread starter Thread starter genc ymeri
  • Start date Start date
G

genc ymeri

Hi,
Coming from another language, I'm getting to unsuspecting surprises. All I
want to do is to add some data in run time a grid, These data are not coming
from a dataset but manually added by an end user over a C# form by clicking
an add button.

So, if I want to have a grid with data as below, which are the proper
components and how can I do that ? (I tried datagrid.sedatabinding but I
couldn't do much with it.)

Name Age Profession

James 23 Developer
Bill 34 Truck Driver
John 55 Sales Manager


Thanks a lot in advance.
 
The data that you want to bind to the grid must be represented in a way
that the datagrid can consume. See
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfSystemWindowsFormsDataGridClassTopic.asp for all of the ways you can
bind data to a datagrid. That said, here's one solution that I came up
with based on your post:

Add a DataTable to your main form class:
private DataTable theTable = null;

Now initialize the DataTable in the constructor:
this.theTable = new DataTable("people"); // or whater you want to name the
table, or you don't even have to name it

// these are the columns in the table
// their headings will show up in the datagrid
this.theTable.Columns.Add("Name");
this.theTable.Columns.Add("Age");
this.theTable.Columns.Add("Profession");

Now add the data to DataTable and bind it to the datagrid:
// this code goes in add button click handler
string[] data = new string[3] { this.textBoxName.Text,
this.textBoxAge.Text, this.textBoxProfession.Text };
this.theTable.Rows.Add(data);
this.dataGrid1.DataSource = this.theTable;

hth

-Joel
--------------------
 
Back
Top