asp.net datagrid为我们提供的内建的记录行编辑功能,但是没有提供内建的添加新行的功能。一个办法就是:在datatable中添加新行,然后再重新绑定到datagrid,这个办法可行,但在更新前需要进行确认,可能会产生空行。另外一个解决办法就是:利用datagrid footer template来提供一个空的行,这样既可以提高速度,也可以避免其它方法带来的不足。
public class insertabledatagrid inherits system.web.ui.page protected withevents datagrid1 as system.web.ui.webcontrols.datagrid
#region " web form designer generated code "
'this call is required by the web form designer. <system.diagnostics.debuggerstepthrough()> private sub initializecomponent()
end sub
private sub page_init(byval sender as system.object, byval e as system.eventargs) handles mybase.init 'codegen: this method call is required by the web form designer 'do not modify it using the code editor. initializecomponent() end sub
#end region
dim connstr as string = "integrated security=sspi;user id=sa;initial catalog=northwind;data source=./netsdk"
private sub page_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load if not page.ispostback then bindgrid() end if end sub
sub bindgrid() dim cnn as new sqlconnection(connstr) dim da as new sqldataadapter("select employeeid,lastname,firstname from employees", cnn) dim ds as new dataset() da.fill(ds, "employees")
datagrid1.datasource = ds datagrid1.databind() end sub private sub datagrid1_itemcommand(byval source as object, byval e as system.web.ui.webcontrols.datagridcommandeventargs)_ handles datagrid1.itemcommand if e.commandname = "insert" then dim cnn as new sqlconnection(connstr) dim t1 as textbox = e.item.findcontrol("textbox2") dim t2 as textbox = e.item.findcontrol("textbox4") cnn.open() dim cmd as new sqlcommand("insert into employees(lastname,firstname) values('" & t1.text & "','" & t2.text & "')", cnn) cmd.executenonquery() cnn.close() bindgrid() end if end sub end class
using system; using system.collections; using system.componentmodel; using system.data; using system.data.sqlclient; using system.drawing; using system.web; using system.web.sessionstate; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.htmlcontrols;
namespace bzh_home { /// <summary> /// appe_admin 的摘要说明。 /// </summary> public class appe_admin : system.web.ui.page { protected system.web.ui.webcontrols.datagrid datagrid1;
private void bindgrid(){ sqlconnection cnn = new sqlconnection(connstr); sqldataadapter da = new sqldataadapter("select * from admin", cnn); dataset ds = new dataset(); da.fill(ds,"admin");