Inserting user input into datagridview

Denumber50

New member
Joined
Jul 1, 2014
Messages
1
Programming Experience
Beginner
I am attempting to get user input and store it into the columns in a datagridview and save it. All of my attempts this far have been unsuccessful. I can get the information to read out on a multi line text, but I assumed you couldn't have sort able columns in c#. If anyone could help me out here I would be much appreciative.
form1.PNGform2.PNG
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,144
Location
Sydney, Australia
Programming Experience
10+
Where are you trying to save it to? A database? If so then you should create a DataTable and bind it to the grid. Adding a new record is then done by adding a new row to that DataTable. I would suggest binding via a BindingSource, which you would add to the form in the designer.
var table = new DataTable();

table.Columns.Add("ID", typeof (int));
table.Columns.Add("Name", typeof (string));

this.bindingSource1.DataSource = table;
this.dataGridView1.DataSource = this.bindingSource1;
You can then add a row directly to the DataTable:
var row = table.NewRow();

row["ID"] = 1;
row["Name"] = "First";

table.Rows.Add(row);
or via the BindingSource:
var row = (DataRowView) this.bindingSource1.AddNew();

row["ID"] = 1;
row["Name"] = "First";

this.bindingSource1.EndEdit();
You then save the changes from the DataTable to the database using a data adapter, just as always.
 
Top Bottom