asp.net datagrid為我們提供的內(nèi)建的記錄行編輯功能,但是沒有提供內(nèi)建的添加新行的功能。一個辦法就是:在datatable中添加新行,然后再重新綁定到datagrid,這個辦法可行,但在更新前需要進行確認,可能會產(chǎn)生空行。另外一個解決辦法就是:利用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");