如何将文本框中的值插入网格视图 [英] How to insert a value from text box to grid view

查看:72
本文介绍了如何将文本框中的值插入网格视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有朋友早上好,





朋友我试图在C#GUI中创建一个表格如下: -



我有4个文本框,1个数据网格Vew和1个按钮。



现在,点击按钮我想以表格的形式将文本框中的所有4条记录添加到数据网格视图中。如下所示: -



名称|部门|年龄|工资

____________________________________________



Hemant | IT | 25 | 10卢比



______________________________________________











能帮我把这些记录插入网格视图。





先谢谢....

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....

推荐答案

这是非常简单的代码试试这个 < br $>


it is very simple code try this

datagridview.Rows.Add(textBox1.text,Textbox2.text,textbox3.text,textbox4.text);


您好,

这是我的解决方案。它是在IDE SharpDevelop C#4.0中构建为windows窗体应用程序

并且需要netframework 4.0。

它包含一个表单,其中包含一个DataGridView,其中有四列符合您的要求,

当你想要将数据从文本框传输到DataGridView时,需要点击四个文本框和一个按钮。



在程序开始时有调用将DataGridView的初始值设置为文本框。查看下面的代码。

它只有一个事件处理程序,它是EnterValuesToDatagridView,当你点击按钮时执行(最初它是Button1Click,但是我喜欢这个名字)。



这个解决方案没有解决案例,如果你需要将输入的数据更改为网格视图怎么办。也许你需要另一个事件,比如用户选择行标题并将数据传回文本框进行更改...



Program.cs *



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*

/*
 * 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 *





MainForm.cs*

/*
 * 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 *





MainFor.Designer.cs*

/*
 * 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[^]


Hope you got it,

Hope you got it,
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();


这篇关于如何将文本框中的值插入网格视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆