How to Populate Data from Textbox to Datagridview in C#/CSharp
The following example allows you to populate data from a TextBox to DataGridView Control in C#/CSharp.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TextBoxToDataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;
//SET DATAGRIDVIEW PROPERTIES
dgv.AutoGenerateColumns = false;
dgv.AllowUserToAddRows = false;
dgv.RowHeadersVisible = false;
dgv.MultiSelect = false;
//SETS UP THE COLUMN HEADERS
dgv.Columns.Add("FName", "First Name");
dgv.Columns.Add("LName", "Last Name");
dgv.Columns.Add("Age", "Age");
}
private void btnAdd_Click(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;
//ADDS NEW DATAGRIDVIEW ROW
dgv.Rows.Add(txtFirstName.Text.ToString());
//ADDS THE SUBITEMS OF THE CURRENTLY ADDED ROW
dgv.Rows[dgv.Rows.Count - 1].Cells[1].Value = txtLastName.Text.ToString();
dgv.Rows[dgv.Rows.Count - 1].Cells[2].Value = Convert.ToInt16(txtAge.Text);
//SELECT THE LAST ROW OF THE DATAGRIDVIEW
dgv.Rows[dgv.Rows.Count - 1].Selected = true;
}
}
}
0 comments: