In this tutorial I’ll show you how to add data from textbox into DataGridView. Firstly I designed the Windows Form Application as following the picture.
I added three textboxes, a button and a gridview. I named textboxs as txtName, txtLastName, txtAge. Also I named the button and the gridview as btnAdd, dataGridViewList.
If you finish the design just double click the btnAdd (button). Now I will appreciate any ideas or solutions on how can we possibly get the values from textboxes on button click
I defined the names of columns in Form1() metod. Form1 method is constructor method of this class and project.
From1() Method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public Form1() { InitializeComponent(); //Construct the datagrid dataGridViewList.ColumnCount = 3; dataGridViewList.Columns[0].Name = "Name"; dataGridViewList.Columns[1].Name = "LastName"; dataGridViewList.Columns[2].Name = "Age"; //for equel width dataGridViewList.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridViewList.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridViewList.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } |
btnAdd Click:
1 2 3 4 5 6 7 |
private void btnAdd_Click(object sender, EventArgs e) { addRow(txtName.Text,txtLastName.Text,txtAge.Text); //alternative 1 dataGridViewList.Rows.Add(txtName.Text, txtLastName.Text, txtAge.Text); //alternative 2 } |
And AddRow Method: (You may aslo add in the btnAdd)
1 2 3 4 5 6 7 |
private void addRow(string name, string lastname, string age) { String[] row = { name, lastname, age }; dataGridViewList.Rows.Add(row); } |
Click HERE to download the example
All Codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DataGridView_Example { public partial class Form1 : Form { public Form1() { InitializeComponent(); //Construct the datagrid dataGridViewList.ColumnCount = 3; dataGridViewList.Columns[0].Name = "Name"; dataGridViewList.Columns[1].Name = "LastName"; dataGridViewList.Columns[2].Name = "Age"; //for equel width dataGridViewList.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridViewList.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridViewList.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } private void btnAdd_Click(object sender, EventArgs e) { addRow(txtName.Text,txtLastName.Text,txtAge.Text); //alternative 1 dataGridViewList.Rows.Add(txtName.Text, txtLastName.Text, txtAge.Text); //alternative 2 } private void addRow(string name, string lastname, string age) { String[] row = { name, lastname, age }; dataGridViewList.Rows.Add(row); } } } |
Output:
Excellent works perfect expect the addRow method, maybe it was updated