Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
1.71/5 (5 votes)
See more:
Dear All Friends good morning,


Friends i m trying to create a form in C# GUI like this:-

I have 4 text Boxes , 1 Data Grid Vew, and 1 Button.

Now, on the button click i want to add all the 4 records from text box to Data Grid view in a form of table . Like below:-

Name | Department | Age | Salary
____________________________________________

Hemant | IT | 25 | 10 rupees

______________________________________________





Can you please help me to insert these record into grid view.


Thanks in Advance....
Posted
Updated 30-Sep-16 4:12am
v3

it is very simple code try this

C#
datagridview.Rows.Add(textBox1.text,Textbox2.text,textbox3.text,textbox4.text);
 
Share this answer
 
Hello,
This is my solution for your problem. It is built as windows form application
in IDE SharpDevelop C# 4.0 and needs netframework 4.0.
It consists of one form with one DataGridView with four columns as you requested,
four text boxes and one button to be clicked when you want to transfer data from text boxes to DataGridView.

At the begining of program there is call for setting initial values of DataGridView an text boxes.Look At the code below.
It has only one event handler and it is EnterValuesToDatagridView, that executes when you click button ( initialy it was Button1Click , but I like this name ).

This solution do not solve case , what if you need to change entered data to grid view. Perhaps you need another event , like user select row heder and transfer data back to text boxes for change...

Program.cs*

C#
/*
 * Created by SharpDevelop.
 * User: Perić Željko
 * Date: 03.03.2012
 * Time: 18:33
 * 
 */
using System;
using System.Windows.Forms;

namespace Insert_value_from_TextBox__to__DataGridView
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}
		
	}
}


MainForm.cs*

C#
/*
 * Created by SharpDevelop.
 * User: Perić Željko
 * Date: 03.03.2012
 * Time: 18:33
 * 
 * Windows form application written in C# 4.0 , needs netframework 4.0
 * 
 * Application for transfering values from text box to DataGridView table
 * 
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Insert_value_from_TextBox__to__DataGridView
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for
                        // Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the
                        // InitializeComponent() call.
			//
			//
			// DataGridView at the begining needs to have at least
                        // one row
			// and text boxes needs its initial values
			//
			
			SetInitialValues();
		}
		
		//
		// When user click on button to enter values from text boxes to
                // grid
		//
		void EnterValuesToDatagridView(object sender, EventArgs e)
		{
			// TODO: Implement Button1Click
				
			//
			// Variable for storing new row number in grid
			//
			int Row = 0;
			
			//
			// Check whether the user has entered all the values
			//
			if (textBox1.Text != "" & textBox2.Text != "" &
                             textBox3.Text != "" & textBox4.Text != "")
			{
				
				//
				// Add new row to DataGridView where the values
                                // are to be entered
				//
				dataGridView1.Rows.Add();
				
				//
				// Get Row number ,
				// it is reduced by two because
				// the first row number is zero, after adding
                                // new row to allready
				// existing one.
				//
				Row = dataGridView1.Rows.Count - 2;
				
				//
				// Store values from text boxes to DataGridView
				//
				dataGridView1[0,Row].Value = textBox1.Text;
				dataGridView1[1,Row].Value = textBox2.Text;
				dataGridView1[2,Row].Value = textBox3.Text;
				dataGridView1[3,Row].Value = textBox4.Text;
				dataGridView1.Refresh();
				
				//
				// This is optional
				// Clear text boxes
				//
				textBox1.Text = "";
				textBox2.Text = "";
				textBox3.Text = "";
				textBox4.Text = "";
			}
			
			//
			// If all text boxes are not filled in
			//
			else
			{
                MessageBox.Show("You did not entered values to all text boxes",
                "Error", MessageBoxButtons.OK,MessageBoxIcon.Error);
			}
		}
		
		void SetInitialValues()
		{
			//
			// This is optional
			// Set DataGridView read only property to true
			// User will not be able to enter values to grid directly
			//
			// And allow user to delete rows 
			//
			dataGridView1.ReadOnly = true;
			dataGridView1.AllowUserToDeleteRows = true;
			
			//
			// Set DataGridView number of rows to one , this is
                        // necessary
			//
			dataGridView1.RowCount = 1;
			dataGridView1.Refresh();
			
			//
			// Set initial values of text box
			//
			textBox1.Text = "Hemant";
			textBox2.Text = "IT";
			textBox3.Text = "25";
			textBox4.Text = "10 rupee";
		}
	}
}


MainFor.Designer.cs*

C#
/*
 * Created by SharpDevelop.
 * User: PC
 * Date: 03.03.2012
 * Time: 18:33
 * 
 */
namespace Insert_value_from_TextBox__to__DataGridView
{
	partial class MainForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		
		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}
		
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
			this.textBox1 = new System.Windows.Forms.TextBox();
			this.textBox2 = new System.Windows.Forms.TextBox();
			this.textBox3 = new System.Windows.Forms.TextBox();
			this.textBox4 = new System.Windows.Forms.TextBox();
			this.button1 = new System.Windows.Forms.Button();
			this.dataGridView1 = new System.Windows.Forms.DataGridView();
			this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
			this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
			this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
			this.Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
			this.SuspendLayout();
			// 
			// textBox1
			// 
			this.textBox1.Location = new System.Drawing.Point(49, 357);
			this.textBox1.Name = "textBox1";
			this.textBox1.Size = new System.Drawing.Size(202, 26);
			this.textBox1.TabIndex = 0;
			// 
			// textBox2
			// 
			this.textBox2.Location = new System.Drawing.Point(257, 357);
			this.textBox2.Name = "textBox2";
			this.textBox2.Size = new System.Drawing.Size(134, 26);
			this.textBox2.TabIndex = 1;
			// 
			// textBox3
			// 
			this.textBox3.Location = new System.Drawing.Point(397, 357);
			this.textBox3.Name = "textBox3";
			this.textBox3.Size = new System.Drawing.Size(51, 26);
			this.textBox3.TabIndex = 2;
			// 
			// textBox4
			// 
			this.textBox4.Location = new System.Drawing.Point(454, 357);
			this.textBox4.Name = "textBox4";
			this.textBox4.Size = new System.Drawing.Size(138, 26);
			this.textBox4.TabIndex = 3;
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(49, 400);
			this.button1.Margin = new System.Windows.Forms.Padding(2);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(543, 31);
			this.button1.TabIndex = 4;
			this.button1.Text = "Enter values to grid";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.EnterValuesToDatagridView);
			// 
			// dataGridView1
			// 
			this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
			this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Sunken;
			dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
			dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
			dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
			dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
			dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
			dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
			dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
			this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
			this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
									this.Column1,
									this.Column2,
									this.Column3,
									this.Column4});
			this.dataGridView1.Location = new System.Drawing.Point(8, 8);
			this.dataGridView1.Margin = new System.Windows.Forms.Padding(2);
			this.dataGridView1.Name = "dataGridView1";
			this.dataGridView1.Size = new System.Drawing.Size(613, 328);
			this.dataGridView1.TabIndex = 5;
			// 
			// Column1
			// 
			this.Column1.HeaderText = "Name";
			this.Column1.Name = "Column1";
			this.Column1.Width = 200;
			// 
			// Column2
			// 
			this.Column2.HeaderText = "Department";
			this.Column2.Name = "Column2";
			this.Column2.Width = 150;
			// 
			// Column3
			// 
			this.Column3.HeaderText = "Age";
			this.Column3.Name = "Column3";
			this.Column3.Width = 50;
			// 
			// Column4
			// 
			this.Column4.HeaderText = "Salary";
			this.Column4.Name = "Column4";
			this.Column4.Width = 150;
			// 
			// MainForm
			// 
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
			this.ClientSize = new System.Drawing.Size(632, 442);
			this.Controls.Add(this.dataGridView1);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.textBox4);
			this.Controls.Add(this.textBox3);
			this.Controls.Add(this.textBox2);
			this.Controls.Add(this.textBox1);
			this.DoubleBuffered = true;
			this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
			this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
			this.Name = "MainForm";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = " Insert value from TextBox  to  DataGridView";
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
			this.ResumeLayout(false);
			this.PerformLayout();
		}
		private System.Windows.Forms.DataGridViewTextBoxColumn Column4;
		private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
		private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
		private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
		private System.Windows.Forms.DataGridView dataGridView1;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.TextBox textBox4;
		private System.Windows.Forms.TextBox textBox3;
		private System.Windows.Forms.TextBox textBox2;
		private System.Windows.Forms.TextBox textBox1;
	}
}



All the best,
Perić Željko

get value from selected rows in datagridview[^]
 
Share this answer
 
v5
Comments
Engr Nouman 29-Dec-15 6:32am    
well this add only 1 row if trying to add second it replace first row how to handle this if want to add more than 2 rows on again and againn button click
Perić Željko 29-Dec-15 12:16pm    
Program code partially solves problem, explained at the beginning of this article. It is possible to adjust it to solve Your problem but it is not recommended. It is better to write new one based on previously acquired knowledge. Try to learn something from articles at submitted links.

All the best,
Željjo Perić
Hope you got it,
C#
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DBname.mdf;Integrated Security=True;User Instance=True");
     conn.Open();
            SqlCommand CmdSql = new SqlCommand("INSERT INTO [Table] (Name, department, age, salary) VALUES (@Name,@dept, @age, @sal)", conn);
                   
            CmdSql.Parameters.AddWithValue("@Name", TextBox1.Text);
            CmdSql.Parameters.AddWithValue("@dept", TextBox2.Text);
            CmdSql.Parameters.AddWithValue("@age", TextBox3.Text);
            CmdSql.Parameters.AddWithValue("@sal", TextBox4.Text);
            CmdSql.ExecuteNonQuery();
            conn.Close();
 
Share this answer
 
Comments
V!jAy pAnT 11-Jul-12 7:49am    
sir... can i also insert the textbox data to gridview's text box on onkeypress or onkeyup event rather pressing the button..... plz reply thanx.
gggustafson 27-Apr-14 13:16pm    
I don't see this as a solution to the question OP asked. The question was "on button click move contents of four TextBoxes to a DataGridView".
Call this after insertion in button event.

HTML
YourGridViewId.DataBind();
 
Share this answer
 
Hi,use the following code

private void button1_Click(object sender, EventArgs e)
        {
            DataRow drow;          
            DataTable dt = SetDataTable();
            drow = dt.NewRow();
            drow["Name"] = textBox1.Text.Trim();
            drow["Department"] = textBox2.Text.Trim();
            drow["Age"] = textBox3.Text.Trim();
            drow["Salary"] = textBox4.Text.Trim();
            dt.Rows.Add(drow);
            BindGrid(dt);
            

        }
        private DataTable SetDataTable()
        {
            DataTable dt = new DataTable();
            try
            {
                DataColumn dcol = new DataColumn("Name", typeof(System.String));
                dt.Columns.Add(dcol);
                dcol = new DataColumn("Department", typeof(System.String));
                dt.Columns.Add(dcol);
                dcol = new DataColumn("Age", typeof(System.String));
                dt.Columns.Add(dcol);
                dcol = new DataColumn("Salary", typeof(System.String));
                dt.Columns.Add(dcol);
            }
            catch (Exception ex)
            {
               
            }
            return dt;
        }
        private void BindGrid(DataTable dt)
        {
            try
            {
                if (dt.Rows.Count > 0)
                {
                    dataGridView1.DataSource = dt;
                    
                }
                else {}
            }
            catch (Exception ex)
            {
                
            }
        }
 
Share this answer
 
C#
private void button_Click(object sender, EventArgs e)
{
     //Check if all the textbox's are not blank. 
     //if not then execute the below lines
     dataGridView1.Rows.Add(1);
     int row = dataGridView1.Rows.Count - 1;
     dataGridView1.Rows[row].Cells[0].Value = Convert.ToString(TextBox1.Text);
     dataGridView1.Rows[row].Cells[1].Value = Convert.ToString(TextBox2.Text);
     dataGridView1.Rows[row].Cells[2].Value = Convert.ToString(TextBox3.Text);
     dataGridView1.Rows[row].Cells[3].Value = Convert.ToString(TextBox4.Text);
}


Hope this will solve ur query.
 
Share this answer
 
Make your insert query like this Insert into
C#
Table('"+textbox1.Text+"','"+Textbox2.text+"',"+textbox3.text+",'"+textbox4.text+"')";

its just a query you'll need to make query and pass parameters in it instead of directly giving values of textbox
 
Share this answer
 
v2
Comments
manojpratap14325 6-Jul-12 7:29am    
ya i have a one textbox one button and a one gridview i have a condition-"if i fill the data in textbox and it is menedetory givin data match with our table data after that i m click on button the corrospondos data show in datagridview "plz help me
V!jAy pAnT 11-Jul-12 7:50am    
sir... can i also insert the textbox data to gridview's text box on onkeypress or onkeyup event rather pressing the button..... plz reply thanx.
You Need To Follow 3 Steps

Step 1

First Make Class

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;

namespace My_Program
{
    public class connectionclass
    {
        public string connectionstring { set; get; }

       public connectionclass()
        {
            connectionstring = @"Add Your Connection String Here";
       }

        public SqlConnection getConnection()
        {
            SqlConnection con = new SqlConnection(connectionstring);

            return con;
        }

        
    }
}


Step 2

Then Make Function
C#
public void Load_My_Function() 
        {
            SqlConnection conn = connect.get_connection();
            string query = @"select * from Your_table_Name;";
            
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(query, conn);
                SqlDataAdapter ada = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                ada.Fill(dt);
                Your_DataGridView.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                
            }

 
        }


Step 3

Then Double Click On Add Button And Write Code

C#
private void add_btn_Click(object sender, EventArgs e)
        {
            

            try
            {
                
                SqlCommand cmd = new SqlCommand(@"insert into user_info values(@Name, @Department, @Age, @salery)");

                cmd.CommandType = CommandType.Text;
                Connection_class con = new Connection_class();
                SqlConnection conn = connect.get_connection();

                cmd.Connection = conn;
                ;
                cmd.Parameters.AddWithValue("@Name", Name_txt.Text.ToString());
                cmd.Parameters.AddWithValue("@Department", Department_txt.Text.ToString());
                cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(Age_txt.Text.ToString()));
                cmd.Parameters.AddWithValue("@Salery", Convert.ToInt32(Salery_txt.Text.ToString()));
                

                
                MessageBox.Show("Your Data Is Successfully Added In The Database");
                conn.Open();
                cmd.ExecuteNonQuery();
                Load_My_Function();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
               
            }
        }
 
Share this answer
 
v2
Comments
[no name] 27-Apr-14 8:14am    
Why are you answering a question that is 2 years old and already has plenty of answers?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900