DataGrid的使用入门(添加、删除和修改操作)[转]

近在做一个管理系统,发现DATAGRID真的很好用,不过用起来有点麻烦,所以转一下相关文章,与大家分享。
  见于好多人在CSDN上问如何在DataGrid中进行添加、删除和修改操作,我最近作了如下一个例子。
 
首先,例子所用的数据库是SQL Server2000,数据库表格如下:
字段名
类型
备注
EmployeeID
Int
自增字段
EmployeeName
Varchar(20)
 
Salary
Int
 
CellPhone
Varchar(20)
 
EmailAddress
Varchar(20)
 
 
程序的代码如下:
ContractedBlock.gif ExpandedBlockStart.gif
None.gif//------------------------Datagrid Demo------------------------------------
None.gif
//-------------------------------------------------------------------------
None.gif
//---File:frmDataGridDemo.cs
None.gif
//---Description:The main form file to operate datagrid 
None.gif
//---Author:Knight
None.gif
//---Date:Mar.17, 2006
None.gif
//-------------------------------------------------------------------------
None.gif
//----------------------{ Datagrid Demo }----------------------------------
None.gif
using System;
None.gif
using System.Drawing;
None.gif
using System.Collections;
None.gif
using System.ComponentModel;
None.gif
using System.Windows.Forms;
None.gif
using System.Data;
None.gif
using System.Data.SqlClient;
None.gif 
None.gif
namespace CSDataGrid
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**////<summary>
InBlock.gif    
/// Summary description for frmDataGridDemo.
ExpandedSubBlockEnd.gif    
///</summary>

InBlock.gif    public class frmDataGridDemo : System.Windows.Forms.Form
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private System.Windows.Forms.DataGrid dtgUserInfo;
InBlock.gif        
private System.Windows.Forms.Button btnUpdate;
InBlock.gif        
private System.Windows.Forms.Button btnExit;
InBlock.gif 
InBlock.gif        
protected SqlConnection sqlConn = new SqlConnection();
InBlock.gif        
protected SqlDataAdapter sqlDAdapter = null;
InBlock.gif        
protected DataSet sqlRecordSet = null;
InBlock.gif 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**////<summary>
InBlock.gif        
/// Required designer variable.
ExpandedSubBlockEnd.gif        
///</summary>

InBlock.gif        private System.ComponentModel.Container components = null;
InBlock.gif 
InBlock.gif        
public frmDataGridDemo()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// Required for Windows Form Designer support
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif 
InBlock.gif            
//
InBlock.gif            
// TODO: Add any constructor code after InitializeComponent call
InBlock.gif            
//
ExpandedSubBlockEnd.gif
        }

InBlock.gif 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**////<summary>
InBlock.gif        
/// Clean up any resources being used.
ExpandedSubBlockEnd.gif        
///</summary>

InBlock.gif        protected override void Dispose( bool disposing )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if( disposing )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (components != null
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    components.Dispose();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
base.Dispose( disposing );
ExpandedSubBlockEnd.gif        }

InBlock.gif 
ContractedSubBlock.gifExpandedSubBlockStart.gif        
Windows Form Designer generated code#region Windows Form Designer generated code
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**////<summary>
InBlock.gif        
/// Required method for Designer support - do not modify
InBlock.gif        
/// the contents of this method with the code editor.
ExpandedSubBlockEnd.gif        
///</summary>

InBlock.gif        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.dtgUserInfo = new System.Windows.Forms.DataGrid();
InBlock.gif            
this.btnUpdate = new System.Windows.Forms.Button();
InBlock.gif            
this.btnExit = new System.Windows.Forms.Button();
InBlock.gif            ((System.ComponentModel.ISupportInitialize)(
this.dtgUserInfo)).BeginInit();
InBlock.gif            
this.SuspendLayout();
InBlock.gif            
// 
InBlock.gif            
// dtgUserInfo
InBlock.gif            
// 
InBlock.gif
            this.dtgUserInfo.DataMember = "";
InBlock.gif            
this.dtgUserInfo.HeaderForeColor = System.Drawing.SystemColors.ControlText;
InBlock.gif            
this.dtgUserInfo.Location = new System.Drawing.Point(816);
InBlock.gif            
this.dtgUserInfo.Name = "dtgUserInfo";
InBlock.gif            
this.dtgUserInfo.Size = new System.Drawing.Size(528480);
InBlock.gif            
this.dtgUserInfo.TabIndex = 0;
InBlock.gif            
// 
InBlock.gif            
// btnUpdate
InBlock.gif            
// 
InBlock.gif
            this.btnUpdate.Location = new System.Drawing.Point(54416);
InBlock.gif            
this.btnUpdate.Name = "btnUpdate";
InBlock.gif            
this.btnUpdate.TabIndex = 1;
InBlock.gif            
this.btnUpdate.Text = "&Update";
InBlock.gif            
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
InBlock.gif            
// 
InBlock.gif            
// btnExit
InBlock.gif            
// 
InBlock.gif
            this.btnExit.Location = new System.Drawing.Point(544472);
InBlock.gif            
this.btnExit.Name = "btnExit";
InBlock.gif            
this.btnExit.TabIndex = 2;
InBlock.gif            
this.btnExit.Text = "E&xit";
InBlock.gif            
// 
InBlock.gif            
// frmDataGridDemo
InBlock.gif            
// 
InBlock.gif
            this.AutoScaleBaseSize = new System.Drawing.Size(513);
InBlock.gif            
this.ClientSize = new System.Drawing.Size(634511);
InBlock.gif            
this.Controls.Add(this.btnExit);
InBlock.gif            
this.Controls.Add(this.btnUpdate);
InBlock.gif            
this.Controls.Add(this.dtgUserInfo);
InBlock.gif            
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
InBlock.gif            
this.MaximizeBox = false;
InBlock.gif            
this.Name = "frmDataGridDemo";
InBlock.gif            
this.Text = "DataGrid Demo";
InBlock.gif            
this.Load += new System.EventHandler(this.frmDataGridDemo_Load);
InBlock.gif            ((System.ComponentModel.ISupportInitialize)(
this.dtgUserInfo)).EndInit();
InBlock.gif            
this.ResumeLayout(false);
InBlock.gif 
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**////<summary>
InBlock.gif        
/// The main entry point for the application.
ExpandedSubBlockEnd.gif        
///</summary>

InBlock.gif        [STAThread]
InBlock.gif        
static void Main() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Application.Run(
new frmDataGridDemo());
ExpandedSubBlockEnd.gif        }

InBlock.gif 
InBlock.gif        
private void frmDataGridDemo_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//Set connection string 
InBlock.gif
            sqlConn.ConnectionString = yourDBConnectionString;
InBlock.gif 
InBlock.gif            
//Connect to DB
InBlock.gif
            if( ConnectDB() )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//Bind data to datagrid
InBlock.gif
                BindData();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif 
InBlock.gif        
private void AddDGStyle()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            DataGridTableStyle ts1 
= new DataGridTableStyle(); 
InBlock.gif 
InBlock.gif            
//specify the table from dataset (required step) 
InBlock.gif
            ts1.MappingName = "EmployeeInfo"
InBlock.gif            PropertyDescriptorCollection pdc 
= this.BindingContext
InBlock.gif                [sqlRecordSet, 
"EmployeeInfo"].GetItemProperties();
InBlock.gif 
InBlock.gif            DataGridColumnStyle TextCol 
= new DataGridTextBoxColumn( pdc["EmployeeID"], "i" );
InBlock.gif            TextCol.MappingName 
= "EmployeeID"
InBlock.gif            TextCol.HeaderText 
= "EmployeeID"
InBlock.gif            TextCol.Width 
= 0
InBlock.gif            TextCol.ReadOnly 
= true;
InBlock.gif            ts1.GridColumnStyles.Add(TextCol); 
InBlock.gif 
InBlock.gif            TextCol 
= new DataGridTextBoxColumn(); 
InBlock.gif            TextCol.MappingName 
= "EmployeeName"
InBlock.gif            TextCol.HeaderText 
= "Employee Name"
InBlock.gif            TextCol.Width 
= 100
InBlock.gif            ts1.GridColumnStyles.Add(TextCol); 
InBlock.gif            
InBlock.gif            TextCol 
= new DataGridTextBoxColumn( pdc["Salary"], "i" );
InBlock.gif            TextCol.MappingName 
= "Salary"
InBlock.gif            TextCol.HeaderText 
= "Salary"
InBlock.gif            TextCol.Width 
= 80
InBlock.gif            ts1.GridColumnStyles.Add(TextCol); 
InBlock.gif            
InBlock.gif            TextCol 
= new DataGridTextBoxColumn(); 
InBlock.gif            TextCol.MappingName 
= "CellPhone"
InBlock.gif            TextCol.HeaderText 
= "Cell Phone"
InBlock.gif            TextCol.Width 
= 80
InBlock.gif            ts1.GridColumnStyles.Add(TextCol); 
InBlock.gif 
InBlock.gif            TextCol 
= new DataGridTextBoxColumn(); 
InBlock.gif            TextCol.MappingName 
= "EmailAddress"
InBlock.gif            TextCol.HeaderText 
= "Email Address"
InBlock.gif            TextCol.Width 
= 100
InBlock.gif            ts1.GridColumnStyles.Add(TextCol); 
InBlock.gif 
InBlock.gif            dtgUserInfo.TableStyles.Add(ts1);
InBlock.gif 
ExpandedSubBlockEnd.gif        }

InBlock.gif 
InBlock.gif        
private void SetDAdapterCommands()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string strQuery = "";
InBlock.gif            SqlParameter sqlParm 
= null;
InBlock.gif            
// Create data adapter with select command
InBlock.gif
            strQuery = "SELECT EmployeeID, EmployeeName, Salary, CellPhone, EmailAddress "
InBlock.gif                
+ " FROM EmployeeInfo";
InBlock.gif            sqlDAdapter 
= new SqlDataAdapter( strQuery, sqlConn );
InBlock.gif            
InBlock.gif            
//Set update command
InBlock.gif
            strQuery = "Update EmployeeInfo SET "
InBlock.gif                
+ " EmployeeName = @EmployeeName, "
InBlock.gif                
+ " Salary = @Salary, "
InBlock.gif                
+ " CellPhone = @CellPhone, "
InBlock.gif                
+ " EmailAddress = @EmailAddress "
InBlock.gif                
+ " WHERE EmployeeID = @EmployeeID ";
InBlock.gif 
InBlock.gif            sqlDAdapter.UpdateCommand 
= new SqlCommand( strQuery, sqlConn );
InBlock.gif            sqlDAdapter.UpdateCommand.Parameters.Add( 
"@EmployeeName", SqlDbType.VarChar,
InBlock.gif                
20"EmployeeName" );
InBlock.gif            sqlParm 
= sqlDAdapter.UpdateCommand.Parameters.Add("@Salary", SqlDbType.Int);
InBlock.gif            sqlParm.SourceColumn 
= "Salary";
InBlock.gif            sqlParm.SourceVersion 
= DataRowVersion.Current;
InBlock.gif            sqlDAdapter.UpdateCommand.Parameters.Add( 
"@CellPhone", SqlDbType.VarChar,
InBlock.gif                
20"CellPhone" );
InBlock.gif            sqlDAdapter.UpdateCommand.Parameters.Add( 
"@EmailAddress", SqlDbType.VarChar,
InBlock.gif                
20"EmailAddress" );
InBlock.gif            sqlParm 
= sqlDAdapter.UpdateCommand.Parameters.Add("@EmployeeID", SqlDbType.Int);
InBlock.gif            sqlParm.SourceColumn 
= "EmployeeID";
InBlock.gif            sqlParm.SourceVersion 
= DataRowVersion.Original;
InBlock.gif 
InBlock.gif            
//Set insert command
InBlock.gif
            strQuery = "INSERT INTO EmployeeInfo ("
InBlock.gif                
+ " EmployeeName, "
InBlock.gif                
+ " Salary, "
InBlock.gif                
+ " CellPhone, "
InBlock.gif                
+ " EmailAddress) "
InBlock.gif                
+ " VALUES ( "
InBlock.gif                
+ " @EmployeeName, "
InBlock.gif                
+ " @Salary, "
InBlock.gif                
+ " @CellPhone, "
InBlock.gif                
+ " @EmailAddress)";
InBlock.gif            sqlDAdapter.InsertCommand 
= new SqlCommand( strQuery, sqlConn );
InBlock.gif            sqlDAdapter.InsertCommand.Parameters.Add( 
"@EmployeeName", SqlDbType.VarChar,
InBlock.gif                
20"EmployeeName" );
InBlock.gif            sqlParm 
= sqlDAdapter.InsertCommand.Parameters.Add("@Salary", SqlDbType.Int);
InBlock.gif            sqlParm.SourceColumn 
= "Salary";
InBlock.gif            sqlParm.SourceVersion 
= DataRowVersion.Current;
InBlock.gif            sqlDAdapter.InsertCommand.Parameters.Add( 
"@CellPhone", SqlDbType.VarChar,
InBlock.gif                
20"CellPhone" );
InBlock.gif            sqlDAdapter.InsertCommand.Parameters.Add( 
"@EmailAddress", SqlDbType.VarChar,
InBlock.gif                
20"EmailAddress" );
InBlock.gif 
InBlock.gif            strQuery 
= "DELETE FROM EmployeeInfo "
InBlock.gif                
+ " WHERE EmployeeID = @EmployeeID ";
InBlock.gif            sqlDAdapter.DeleteCommand 
= new SqlCommand( strQuery, sqlConn );
InBlock.gif            sqlParm 
= sqlDAdapter.DeleteCommand.Parameters.Add("@EmployeeID", SqlDbType.Int);
InBlock.gif            sqlParm.SourceColumn 
= "EmployeeID";
InBlock.gif            sqlParm.SourceVersion 
= DataRowVersion.Original;
ExpandedSubBlockEnd.gif        }

InBlock.gif 
InBlock.gif        
private void BindData()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SetDAdapterCommands();
InBlock.gif 
InBlock.gif            
//Fill dataset
InBlock.gif
            sqlRecordSet = new DataSet();
InBlock.gif            sqlDAdapter.Fill( sqlRecordSet, 
"EmployeeInfo" );
InBlock.gif 
InBlock.gif            
//Bind datagrid with dataset
InBlock.gif
            dtgUserInfo.SetDataBinding( sqlRecordSet, "EmployeeInfo");
InBlock.gif 
InBlock.gif            
//Add datagrid style
InBlock.gif
            AddDGStyle();
ExpandedSubBlockEnd.gif        }

InBlock.gif 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**////<summary>
InBlock.gif        
/// Connect to DB
InBlock.gif        
///</summary>
ExpandedSubBlockEnd.gif        
///<returns>If connected, return True; else return False</returns>

InBlock.gif        private bool ConnectDB()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//Check current connection's state
InBlock.gif
            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if(     sqlConn.State == ConnectionState.Closed
InBlock.gif                    
|| sqlConn.State == ConnectionState.Broken )
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
//Connection is not available
InBlock.gif
                    sqlConn.Close();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
InBlock.gif                    
//Connection is available
InBlock.gif
                    return true;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif            
catchdot.gif{};
InBlock.gif 
InBlock.gif            
//Re-connect
InBlock.gif
            try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                sqlConn.Open();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch(SqlException e) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//Sql's exception
InBlock.gif
                MessageBox.Show( e.Message );
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch(Exception e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//Other exception
InBlock.gif
                MessageBox.Show( e.Message );
ExpandedSubBlockEnd.gif            }

InBlock.gif 
InBlock.gif            
if(     sqlConn.State == ConnectionState.Closed
InBlock.gif                
|| sqlConn.State == ConnectionState.Broken )
InBlock.gif                
//Connection is not available
InBlock.gif
                return false;
InBlock.gif            
else
InBlock.gif                
//Connection is available
InBlock.gif
                return true;
ExpandedSubBlockEnd.gif        }

InBlock.gif 
InBlock.gif        
private void btnUpdate_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            sqlDAdapter.Update( sqlRecordSet, 
"EmployeeInfo" );
InBlock.gif            sqlRecordSet.Tables[
"EmployeeInfo"].Rows.Clear();
InBlock.gif            sqlDAdapter.Fill( sqlRecordSet, 
"EmployeeInfo" );
ExpandedSubBlockEnd.gif        }

InBlock.gif 
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

       上面的代码有很多细节没有作处理,因此仅仅演示如何对DataGrid操作。
posted on 2006-03-31 13:10 马牛 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/manio/archive/2006/03/31/363504.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值