完全用编码实现gridview创建和clounms的添加Word文件下载.docx
《完全用编码实现gridview创建和clounms的添加Word文件下载.docx》由会员分享,可在线阅读,更多相关《完全用编码实现gridview创建和clounms的添加Word文件下载.docx(7页珍藏版)》请在冰豆网上搜索。
SqlDataSource1.UpdateCommand=
updateemployeessetfirstname=@FirstName,lastname=@LastNamewhereemployeeid=@EmployeeID"
SqlDataSource1.UpdateParameters.Add("
@FirstName"
"
);
@LastName"
@EmployeeID"
if(!
IsPostBack)
GridView1.DataSourceID="
SqlDataSource1"
GridView1.AutoGenerateColumns=false;
GridView1.DataKeyNames=newstring[]{"
EmployeeID"
};
GridView1.AllowPaging=true;
GridView1.AllowSorting=true;
GridView1.PageSize=5;
BoundFieldbf1=newBoundField();
BoundFieldbf2=newBoundField();
BoundFieldbf3=newBoundField();
bf1.HeaderText="
EmployeeID"
bf1.DataField="
bf1.ReadOnly=true;
bf1.SortExpression="
bf2.HeaderText="
FirstName"
bf2.DataField="
FirstName"
bf2.SortExpression="
bf3.HeaderText="
LastName"
bf3.DataField="
LastName"
bf3.SortExpression="
CommandFieldcf=newCommandField();
cf.ButtonType=ButtonType.Button;
cf.ShowCancelButton=true;
cf.ShowEditButton=true;
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(cf);
}
Part2
Introduction
InPart1
youlearnedtocreateBoundFieldsandCommandFieldsdynamically.Oftenyourgridlayoutisbeyondthecapabilitiesofin-builtcolumntypesandyouneedtouseTemplateFields.Forexample,let'
ssayyouarecreatingaproductcatalog.
Certainlynormal
tabularlayoutisnotsuitablehereasyouwanttodisplayeachrecordinahighlycustomizedformat.Templatefieldscancomehandyinsuchsituations.InthisarticleIamgoingtoillustratehowtemplatefieldscanbeaddeddynamically.Youwilllearntwotechniquesofdoingso:
∙UsingLoadTemplate()method
∙Bycreatingacustomtemplateclass
AddingTemplateFieldsUsingLoadTemplate()Method
InordertoworkwiththisexampleyouneedtocreateanewwebsiteinVisualStudio.DraganddropaGridViewonthedefaultpage.AlsodraganddropanSqlDataSourcecontrol.Wewillbesettingvariouspropertiesofthesecontrolsviacode.InthefirstmethodofaddingtemplatefieldswewillbeusingLoadTemplate()method.TheLoadTemplate()methodisavailabletoalltemplatecontrolsincludingthePage.Itaccepts
virtualpathofafileandloadsthetemplatespecifiedtherein.ThereturnvalueofLoadTemplate()isanobjectthatimplementsITemplateinterface.
InourexamplewewillcreatethetemplateinaUserControl.Todoso,addanewWebUserControltothewebsiteandnameitasItemTemplate.ascx.Keyinthefollowingmarkuptoit.
<
%@ControlLanguage="
C#"
AutoEventWireup="
true"
CodeFile="
ItemTemplate.ascx.cs"
Inherits="
ItemTemplate"
%>
asp:
LabelID="
Label1"
runat="
server"
Text='
%#Eval("
)%>
'
>
/asp:
Label>
Label2"
Label3"
Noticeabovemarkupcarefully.ItcontainsthreeLabelcontrols.TheTextpropertyofeachLabelisboundwithEmployeeID,FirstNameandLastNamecolumnsofEmployeestablerespectively.TheEval()expressionisonewaydatabindingexpressionofASP.NETandacceptsthenameofthecolumntobind.ThisusercontrolwillactasourItemTemplatelater.
NowopenthecodebehindfileofthedefaultwebformandkeyinthefollowingcodeinPage_Loadeventhandler.
SqlDataSource1.ConnectionString=
SqlDataSource1.SelectCommand=
TemplateFieldtf1=newTemplateField();
tf1.ItemTemplate=LoadTemplate("
ItemTemplate.ascx"
GridView1.Columns.Add(tf1);
Thecode
pointstheConnectionStringpropertyofSQLdatasourcecontroltoNorthwinddatabase.TheSelectCommandpropertyspecifiesaSELECTstatementthatfetchesEmployeeID,FirstNameandLastNamecolumnsofEmployeestable.Next,itsetsDataSourceIDpropertyofGridViewcontroltotheIDofSQLDataSourcecontrol.Also,AutoGenerateColumnspropertyissettofalseaswewillbeaddingcolumnsprogrammatically.Nextfewlinesareimportant.ThecodethencreatesaninstanceofTemplateFieldclass.TheTemplateFieldclassrepresentsatemplatecolumnofGridViewclass.TheItemTemplatepropertyofTemplateFieldclassisthensettothereturnvalueofLoadTemplate()method.TheLoadTemplate()methodacceptsavirtualpathofthefilecontainingtemplatetobeloaded(ItemTemplate.ascxinourcase).TheTemplateFieldisthenaddedtotheColumnscollectionofGridViewcontrol.
Runthewebformandyourbrowsershoulddisplaysomethingasshownbelow:
Noticehowthetemplatespecifiedintheusercontrolisapplied.Also,noticethatheaderisshownblankbecausewedidnotspecifiedHeaderTemplate.Youcaneitherspecifyitorturntheheaderoff.
AddingTemplateFieldUsingCustomTemplateClass
NowthatyouknowhowtouseLoadTemplate()methodlet'
smovetoanotherpossibility.YoulearntinthelastexamplethatLoadTemplate()methodreturnsanobjectthatimplementsITemplateinterface.YouyourselfcancreatesuchaclassanduseitdirectlyinyourcodeinsteadofusingLoadTemplate()method.
TobeginwithaddanewclassnamedMyTemplatetoApp_Codefolder.KeyinthefollowingcodetoMyTemplateclass.
publicclassMyTemplate:
ITemplate
privatestringcolname;
publicMyTemplate(stringcolname)
{
this.colname=colname;
}
publicvoidInstantiateIn(Controlcontainer)
LiteralControll=newLiteralControl();
l.DataBinding+=newEventHandler(this.OnDataBinding);
container.Controls.Add(l);
publicvoidOnDataBinding(objectsender,EventArgse)
LiteralControll=(LiteralControl)sender;
GridViewRowcontainer=(GridViewRow)l.NamingContainer;
l.Text=((DataRowView)container.DataItem)[colname].ToString();
ThecodecreatesaclasscalledMyTemplatethatimplementsITemplateinterface.TheITemplateinterfacecontainsasinglemethod-InstantiateIn()-thatyoumustimplement.Thecodethendeclaresastringvariabletoholdacolumnnametobedisplayed.Thecolumnnameissetintheconstructoroftheclass.ThenInstantiateIn()methodisimplemented.ThemethodreceivesanobjectoftypeControlthatrepresentscontainerorparentcontrol.InsidewecreateaLiteralControlandattachaneventhandler(OnDataBinding)toitsDataBindingevent.ThiseventisraisedwhenthecontainercontrolcallsDataBind()methodonitself.TheLiteralControlisthenaddedtotheControlscollectionofthecontainercontrol.
TheOnDataBinding()eventhandlerdoesthejobofdatabindingtheLiteralControlwiththerequireddata.ItthengetsareferencetotherowinwhichthecontrolisbeingaddedusingNamingContainerproperty.Finally,TextpropertyofLiteralControlissettothevalueofdatabasecolumnasspecifiedintheconstructor.Thiscompletesourcustomtemplateclass.
Nowaddanewwebformtothesamewebsite.DraganddropaGridViewandSqlDataSourcecontrolasbefore.AddthefollowingcodeinthePage_Loadeventhandleroftheform.
initialcatalog=northwind;
integratedsecurity=true"
MyTemplatet1=newMyTemplate("
tf1.HeaderText="
tf1.ItemTemplate=t1;
TemplateFieldtf2=newTemplateField();
MyTemplatet2=newMyTemplate("
tf2.HeaderText="
tf2.ItemTemplate=t2;
GridView1.Columns.Add(tf2);
ThecodesetsthepropertiesofSqlDataSourceandGridViewasbefore.Noticethecodemarkedinboldletters.ThecodecreatesaninstanceofTemplateFieldclassasbefore.ThistimetheItemTemplatepropertyofTemplateFieldissettoanewinstanceofMyTemplateclass.Thecolumnnames-FirstNameandLastName-arepassedintheconstructor.Finally,thetemplatefieldsareaddedtotheColumnscollectionofGridViewclass.
Thefollowingscreenshotshowsasamplerunoftheabove
webform.
That'
sit!
Happycoding.