gridview详解(2010.10.23)


GridView

自动套用格式可以改变风格。

绑定数据:

要加入命名空间:using system.data.sqlclient;

public void getData()

{
 sqlconnection cn=new sqlconnection("server=localhost;database=northwind;user=sa;password=sa"); //连接数据库

 sqlcommand cmd=new sqlcommand("select * from customers",cn);
 sqldataAdapter da=new sqldataAdapter(cmd);//适配器
 dataset ds=new dataset();//取出数据放到ds中
 da.fill(ds,"customers");
 this.gridview1.datasource=ds.table[0].defaultveiew;
 this.databind();
 

}

调试程序:

用打断点,在即时窗口中加入ds.table[0].rows.count

通过改变sql语句来改变显示数据。


客户控件:

autogeneratecolumns 改为false

在gridview的属性中的columns来改变选择性的改变列。

中的boundfield来绑定列.改变headertext列头名称。datafield来选择要改变的列。


分页:

allowpaging改为ture

在事件中pageindexchanging中代码

this.gridview1.pageindex=e.newpageindex;
getdata();


网格的编辑:

在属性中columns中的commandfield里选项加了编辑、选择、删除后。

在事件中selectedindexchanging选择行

rowdeleting行删除

string customerID=this.gridview1.datakeys[e.rowindex][0].tostring;
deletecustomers(cusotmerID);
getdata();

 

rowediting行编辑

this.gridview1.editindex=e.neweditindex;
getdata();


rowupdating提交数据

改gridview属性datakeynames写入关键字,也就是数据库列名称
string customerID=this.gridview1.datakeys[e.rowindex][0].tostring;
string companyname=(textbox)this.gridview1.rows[e.rowindex].cells[0].controls[0].text.tostring();
string contctname=(textbox)this.gridview1.rows[e.rowindex].cells[1].controls[1].text.tostring();
//response.write(cus+"---"+companyname);
updatacustomers(customerID,companyname,contctname);
this.gridview1.editindex=-1;//脱离编辑状态
getdata();


rowcancelinedit取消

this.gridview1.editindex=-1;
getdata();

 


public void updatacustomers(string customerID,string companyname,string contctname)
{
 sqlconnection cn=new sqlconnection("server=localhost;database=northwind;user=sa;password=sa"); //连接数据库
 sqlcommand cmd new sqlcommand("update customers set companyname='"+companyname"'....where customerID='"+customerID+"'",cn);
 cn.open();
 cmd.executenonquery();//跟数据库提交
 cn.close();
 
}
public void deletecustomers(string customerID)
{
sqlconnection cn=new sqlconnection("server=localhost;database=northwind;user=sa;password=sa"); //连接数据库
 sqlcommand cmd new sqlcommand("delete from customer where customerID='"+customerID+"'",cn);
 cn.open();
 cmd.executenonquery();//跟数据库提交
 cn.close();
 
}
 

 


 

posted @ 2010-10-23 00:07  我是一根葱  阅读(232)  评论(0)    收藏  举报