如何在DataGrid中进行添加、删除和修改操作

见于好多人在CSDN上问如何在DataGrid中进行添加、删除和修改操作,我最近作了如下一个例子。

 

首先,例子所用的数据库是SQL Server2000,数据库表格如下:

字段名

类型

备注

EmployeeID

Int

自增字段

EmployeeName

Varchar(20)

 

Salary

Int

 

CellPhone

Varchar(20)

 

EmailAddress

Varchar(20)

 

 

程序的代码如下:

//------------------------Datagrid Demo------------------------------------

//-------------------------------------------------------------------------

//---File:frmDataGridDemo.cs

//---Description:The main form file to operate datagrid

//---Author:Knight

//---Date:Mar.17, 2006

//-------------------------------------------------------------------------

//----------------------{ Datagrid Demo }----------------------------------

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Data.SqlClient;

 

namespace CSDataGrid

{

    /// <summary>

    /// Summary description for frmDataGridDemo.

    /// </summary>

    public class frmDataGridDemo : System.Windows.Forms.Form

    {

        private System.Windows.Forms.DataGrid dtgUserInfo;

        private System.Windows.Forms.Button btnUpdate;

        private System.Windows.Forms.Button btnExit;

 

        protected SqlConnection sqlConn = new SqlConnection();

        protected SqlDataAdapter sqlDAdapter = null;

        protected DataSet sqlRecordSet = null;

 

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.Container components = null;

 

        public frmDataGridDemo()

        {

            //

            // Required for Windows Form Designer support

            //

            InitializeComponent();

 

            //

            // TODO: Add any constructor code after InitializeComponent call

            //

        }

 

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        protected override void Dispose( bool disposing )

        {

            if( disposing )

            {

                if (components != null)

                {

                    components.Dispose();

                }

            }

            base.Dispose( disposing );

        }

 

        #region Windows Form Designer generated code

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.dtgUserInfo = new System.Windows.Forms.DataGrid();

            this.btnUpdate = new System.Windows.Forms.Button();

            this.btnExit = new System.Windows.Forms.Button();

            ((System.ComponentModel.ISupportInitialize)(this.dtgUserInfo)).BeginInit();

            this.SuspendLayout();

            //

            // dtgUserInfo

            //

            this.dtgUserInfo.DataMember = "";

            this.dtgUserInfo.HeaderForeColor = System.Drawing.SystemColors.ControlText;

            this.dtgUserInfo.Location = new System.Drawing.Point(8, 16);

            this.dtgUserInfo.Name = "dtgUserInfo";

            this.dtgUserInfo.Size = new System.Drawing.Size(528, 480);

            this.dtgUserInfo.TabIndex = 0;

            //

            // btnUpdate

            //

            this.btnUpdate.Location = new System.Drawing.Point(544, 16);

            this.btnUpdate.Name = "btnUpdate";

            this.btnUpdate.TabIndex = 1;

            this.btnUpdate.Text = "&Update";

            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);

            //

            // btnExit

            //

            this.btnExit.Location = new System.Drawing.Point(544, 472);

            this.btnExit.Name = "btnExit";

            this.btnExit.TabIndex = 2;

            this.btnExit.Text = "E&xit";

            //

            // frmDataGridDemo

            //

            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

            this.ClientSize = new System.Drawing.Size(634, 511);

            this.Controls.Add(this.btnExit);

            this.Controls.Add(this.btnUpdate);

            this.Controls.Add(this.dtgUserInfo);

            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

            this.MaximizeBox = false;

            this.Name = "frmDataGridDemo";

            this.Text = "DataGrid Demo";

            this.Load += new System.EventHandler(this.frmDataGridDemo_Load);

            ((System.ComponentModel.ISupportInitialize)(this.dtgUserInfo)).EndInit();

            this.ResumeLayout(false);

 

        }

        #endregion

 

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [STAThread]

        static void Main ()

        {

            Application.Run(new frmDataGridDemo());

        }

 

        private void frmDataGridDemo_Load(object sender, System.EventArgs e)

        {

            //Set connection string

            sqlConn.ConnectionString = yourDBConnectionString;

 

            //Connect to DB

            if( ConnectDB() )

            {

                //Bind data to datagrid

                BindData();

            }

        }

 

        private void AddDGStyle()

        {

            DataGridTableStyle ts1 = new DataGridTableStyle();

 

            //specify the table from dataset (required step)

            ts1.MappingName = "EmployeeInfo";

            PropertyDescriptorCollection pdc = this.BindingContext

                [sqlRecordSet, "EmployeeInfo"].GetItemProperties();

 

            DataGridColumnStyle TextCol = new DataGridTextBoxColumn( pdc["EmployeeID"], "i" );

            TextCol.MappingName = "EmployeeID";

            TextCol.HeaderText = "EmployeeID";

            TextCol.Width = 0;

            TextCol.ReadOnly = true;

            ts1.GridColumnStyles.Add(TextCol);

 

            TextCol = new DataGridTextBoxColumn();

            TextCol.MappingName = "EmployeeName";

            TextCol.HeaderText = "Employee Name";

            TextCol.Width = 100;

            ts1.GridColumnStyles.Add(TextCol);

           

            TextCol = new DataGridTextBoxColumn( pdc["Salary"], "i" );

            TextCol.MappingName = "Salary";

            TextCol.HeaderText = "Salary";

            TextCol.Width = 80;

            ts1.GridColumnStyles.Add(TextCol);

           

            TextCol = new DataGridTextBoxColumn();

            TextCol.MappingName = "CellPhone";

            TextCol.HeaderText = "Cell Phone";

            TextCol.Width = 80;

            ts1.GridColumnStyles.Add(TextCol);

 

            TextCol = new DataGridTextBoxColumn();

            TextCol.MappingName = "EmailAddress";

            TextCol.HeaderText = "Email Address";

            TextCol.Width = 100;

            ts1.GridColumnStyles.Add(TextCol);

 

            dtgUserInfo.TableStyles.Add(ts1);

 

        }

 

        private void SetDAdapterCommands()

        {

            string strQuery = "";

            SqlParameter sqlParm = null;

            // Create data adapter with select command

            strQuery = "SELECT EmployeeID, EmployeeName, Salary, CellPhone, EmailAddress "

                + " FROM EmployeeInfo";

            sqlDAdapter = new SqlDataAdapter( strQuery, sqlConn );

           

            //Set update command

            strQuery = "Update EmployeeInfo SET "

                + " EmployeeName = @EmployeeName, "

                + " Salary = @Salary, "

                + " CellPhone = @CellPhone, "

                + " EmailAddress = @EmailAddress "

                + " WHERE EmployeeID = @EmployeeID ";

 

            sqlDAdapter.UpdateCommand = new SqlCommand( strQuery, sqlConn );

            sqlDAdapter.UpdateCommand.Parameters.Add( "@EmployeeName", SqlDbType.VarChar,

                20, "EmployeeName" );

            sqlParm = sqlDAdapter.UpdateCommand.Parameters.Add("@Salary", SqlDbType.Int);

            sqlParm.SourceColumn = "Salary";

            sqlParm.SourceVersion = DataRowVersion.Current;

            sqlDAdapter.UpdateCommand.Parameters.Add( "@CellPhone", SqlDbType.VarChar,

                20, "CellPhone" );

            sqlDAdapter.UpdateCommand.Parameters.Add( "@EmailAddress", SqlDbType.VarChar,

                20, "EmailAddress" );

            sqlParm = sqlDAdapter.UpdateCommand.Parameters.Add("@EmployeeID", SqlDbType.Int);

            sqlParm.SourceColumn = "EmployeeID";

            sqlParm.SourceVersion = DataRowVersion.Original;

 

            //Set insert command

            strQuery = "INSERT INTO EmployeeInfo ("

                + " EmployeeName, "

                + " Salary, "

                + " CellPhone, "

                + " EmailAddress) "

                + " VALUES ( "

                + " @EmployeeName, "

                + " @Salary, "

                + " @CellPhone, "

                + " @EmailAddress)";

            sqlDAdapter.InsertCommand = new SqlCommand( strQuery, sqlConn );

            sqlDAdapter.InsertCommand.Parameters.Add( "@EmployeeName", SqlDbType.VarChar,

                20, "EmployeeName" );

            sqlParm = sqlDAdapter.InsertCommand.Parameters.Add("@Salary", SqlDbType.Int);

            sqlParm.SourceColumn = "Salary";

            sqlParm.SourceVersion = DataRowVersion.Current;

            sqlDAdapter.InsertCommand.Parameters.Add( "@CellPhone", SqlDbType.VarChar,

                20, "CellPhone" );

            sqlDAdapter.InsertCommand.Parameters.Add( "@EmailAddress", SqlDbType.VarChar,

                20, "EmailAddress" );

 

            strQuery = "DELETE FROM EmployeeInfo "

                + " WHERE EmployeeID = @EmployeeID ";

            sqlDAdapter.DeleteCommand = new SqlCommand( strQuery, sqlConn );

            sqlParm = sqlDAdapter.DeleteCommand.Parameters.Add("@EmployeeID", SqlDbType.Int);

            sqlParm.SourceColumn = "EmployeeID";

            sqlParm.SourceVersion = DataRowVersion.Original;

        }

 

        private void BindData()

        {

            SetDAdapterCommands();

 

            //Fill dataset

            sqlRecordSet = new DataSet();

            sqlDAdapter.Fill( sqlRecordSet, "EmployeeInfo" );

 

            //Bind datagrid with dataset

            dtgUserInfo.SetDataBinding( sqlRecordSet, "EmployeeInfo");

 

            //Add datagrid style

            AddDGStyle();

        }

 

        /// <summary>

        /// Connect to DB

        /// </summary>

        /// <returns>If connected, return True; else return False</returns>

        private bool ConnectDB()

        {

            //Check current connection's state

            try

            {

                if(     sqlConn.State == ConnectionState.Closed

                    ||  sqlConn.State == ConnectionState.Broken )

                {

                    //Connection is not available

                    sqlConn.Close();

                }

                else

                    //Connection is available

                    return true;

            }

            catch{};

 

            //Re-connect

            try

            {

                sqlConn.Open();

            }

            catch(SqlException e)

            {

                //Sql's exception

                MessageBox.Show( e.Message );

            }

            catch(Exception e)

            {

                //Other exception

                MessageBox.Show( e.Message );

            }

 

            if(     sqlConn.State == ConnectionState.Closed

                ||  sqlConn.State == ConnectionState.Broken )

                //Connection is not available

                return false;

            else

                //Connection is available

                return true;

        }

 

        private void btnUpdate_Click(object sender, System.EventArgs e)

        {

            sqlDAdapter.Update( sqlRecordSet, "EmployeeInfo" );

            sqlRecordSet.Tables["EmployeeInfo"].Rows.Clear();

            sqlDAdapter.Fill( sqlRecordSet, "EmployeeInfo" );

        }

 

    }

}

 

       上面的代码有很多细节没有作处理,因此仅仅演示如何对DataGrid操作。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
好的,这个需求需要用到ADO.NET来连接数据库进行操作。以下是一个简单的实现步骤: 1. 创建一个新的Windows Forms应用程序项目。 2. 在主窗体添加一个DataGridView控件,设置其数据源为一个BindingSource对象。 3. 创建一个新的DataSet对象,并添加一个DataTable对象,用于存储学生信息。 4. 使用DataAdapter对象将DataTable对象与数据库的表关联起来。 5. 在主窗体添加添加”、“修改”和“删除”按钮,并为每个按钮添加单击事件处理程序。 6. 在单击“添加”按钮时,打开一个新的窗体,允许用户输入学生信息,并将信息添加到DataTable对象。 7. 在单击“修改”按钮时,获取当前选定的行,并打开一个新的窗体,允许用户编辑学生信息,并将修改后的信息更新到DataTable对象。 8. 在单击“删除”按钮时,获取当前选定的行,并弹出一个确认对话框,如果用户确认删除,则从DataTable对象删除该行数据,并使用DataAdapter对象将修改后的DataTable对象更新到数据库。 9. 在每个操作成功后,使用MessageBox.Show()方法给出提示。 以下是一个示例代码,用于添加学生信息: ``` private void btnAdd_Click(object sender, EventArgs e) { // 打开新窗体,允许用户输入学生信息 AddStudentForm addForm = new AddStudentForm(); DialogResult result = addForm.ShowDialog(); if (result == DialogResult.OK) { // 将学生信息添加到DataTable DataRow row = studentDataTable.NewRow(); row["Name"] = addForm.StudentName; row["Age"] = addForm.StudentAge; row["Gender"] = addForm.StudentGender; studentDataTable.Rows.Add(row); // 使用DataAdapter对象将修改后的DataTable更新到数据库 SqlCommandBuilder builder = new SqlCommandBuilder(adapter); adapter.Update(studentDataTable); // 刷新DataGridView并给出提示 bindingSource.ResetBindings(false); MessageBox.Show("添加成功!"); } } ``` 你可以参考以上代码来实现修改删除功能。需要注意的是,由于修改删除涉及到数据库的操作,需要使用DataAdapter对象更新DataTable对象和数据库的表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值