您的位置:首页 > 其它

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

2006-04-01 13:05 716 查看
最近在做一个管理系统,发现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 );


}







Windows Form Designer generated code#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操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐