导航

如何在DataGrid中添加AutoIncrease的列

Posted on 2004-08-30 11:07  yinzx  阅读(486)  评论(0)    收藏  举报
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace yinzx
{
    
public class DemoAutoIncreaseRowID:Form
    
{
        [STAThread]
        
public static void Main() 
        
{
            Application.Run(
new DemoAutoIncreaseRowID());
        }

        
public DemoAutoIncreaseRowID()
        
{
            
//设置连接字符串及查询语句
            string strCnn = "User ID=sa;Password=zhang;Data Source=zzy;Initial Catalog=pubs";
            
string strSql = "Select fname,lname From employee";
            SqlDataAdapter da 
= new SqlDataAdapter(strSql,strCnn);

            
//获取Employee表的结构(Schema)
            DataSet ds = new DataSet();
            da.FillSchema(ds,SchemaType.Source,
"Employee");
            DataTable t 
= ds.Tables["Employee"];

            
//在原有表结构的基础上加入一个列,用来保存自动增加的列号
            DataColumn c = t.Columns.Add("RowID",typeof(int));
            c.AutoIncrement 
= true;
            c.AutoIncrementSeed 
= 1;
            c.AutoIncrementStep 
= 1;

            
//填充数据到DataSet中,并设置RowFilter
            da.Fill(ds,"Employee");
            DataView dv 
= new DataView(t);
            dv.RowFilter 
= "RowID >10 And RowID<20";

            
//将数据绑定到DataGrid上
            DataGrid grd = new DataGrid();
            
this.Controls.Add(grd);
            grd.Dock 
= DockStyle.Fill;
            grd.DataSource 
= dv;
        }

    }

}

参考资料:《ADO.NET 技术内幕》,7-302-07203-5/TP·5245,第201页