完全用编码实现gridview创建和clounms的添加.docx
《完全用编码实现gridview创建和clounms的添加.docx》由会员分享,可在线阅读,更多相关《完全用编码实现gridview创建和clounms的添加.docx(7页珍藏版)》请在冰豆网上搜索。
完全用编码实现gridview创建和clounms的添加
完全用编码实现gridview创建和clounms的添加。
Part1
protectedvoidPage_Load(objectsender,EventArgse)
{
SqlDataSource1.ConnectionString=
@"datasource=.;initialcatalog=northwind;integratedsecurity=true";
SqlDataSource1.SelectCommand=
"selectemployeeID,FirstName,LastNamefromemployees";
SqlDataSource1.UpdateCommand=
"updateemployeessetfirstname=@FirstName,lastname=@LastNamewhereemployeeid=@EmployeeID";
SqlDataSource1.UpdateParameters.Add("@FirstName","");
SqlDataSource1.UpdateParameters.Add("@LastName","");
SqlDataSource1.UpdateParameters.Add("@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="EmployeeID";
bf1.ReadOnly=true;
bf1.SortExpression="EmployeeID";
bf2.HeaderText="FirstName";
bf2.DataField="FirstName";
bf2.SortExpression="FirstName";
bf3.HeaderText="LastName";
bf3.DataField="LastName";
bf3.SortExpression="LastName";
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);
}
}
完全用编码实现gridview创建和clounms的添加。
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"%>
LabelID="Label1"runat="server"
Text='<%#Eval("EmployeeID")%>'>
Label>
LabelID="Label2"runat="server"
Text='<%#Eval("FirstName")%>'>
Label>
LabelID="Label3"runat="server"
Text='<%#Eval("LastName")%>'>
Label>
Noticeabovemarkupcarefully.ItcontainsthreeLabelcontrols.TheTextpropertyofeachLabelisboundwithEmployeeID,FirstNameandLastNamecolumnsofEmployeestablerespectively.TheEval()expressionisonewaydatabindingexpressionofASP.NETandacceptsthenameofthecolumntobind.ThisusercontrolwillactasourItemTemplatelater.
NowopenthecodebehindfileofthedefaultwebformandkeyinthefollowingcodeinPage_Loadeventhandler.
protectedvoidPage_Load(objectsender,EventArgse)
{
SqlDataSource1.ConnectionString=
@"datasource=.;initialcatalog=northwind;integratedsecurity=true";
SqlDataSource1.SelectCommand=
"selectemployeeID,FirstName,LastNamefromemployees";
if(!
IsPostBack)
{
GridView1.DataSourceID="SqlDataSource1";
GridView1.AutoGenerateColumns=false;
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.
protectedvoidPage_Load(objectsender,EventArgse)
{
SqlDataSource1.ConnectionString=
@"datasource=.;initialcatalog=northwind;integratedsecurity=true";
SqlDataSource1.SelectCommand=
"selectemployeeID,FirstName,LastNamefromemployees";
if(!
IsPostBack)
{
GridView1.DataSourceID="SqlDataSource1";
GridView1.AutoGenerateColumns=false;
TemplateFieldtf1=newTemplateField();
MyTemplatet1=newMyTemplate("FirstName");
tf1.HeaderText="FirstName";
tf1.ItemTemplate=t1;
TemplateFieldtf2=newTemplateField();
MyTemplatet2=newMyTemplate("LastName");
tf2.HeaderText="LastName";
tf2.ItemTemplate=t2;
GridView1.Columns.Add(tf1);
GridView1.Columns.Add(tf2);
}
}
ThecodesetsthepropertiesofSqlDataSourceandGridViewasbefore.Noticethecodemarkedinboldletters.ThecodecreatesaninstanceofTemplateFieldclassasbefore.ThistimetheItemTemplatepropertyofTemplateFieldissettoanewinstanceofMyTemplateclass.Thecolumnnames-FirstNameandLastName-arepassedintheconstructor.Finally,thetemplatefieldsareaddedtotheColumnscollectionofGridViewclass.
Thefollowingscreenshotshowsasamplerunoftheabove webform.
That'sit!
Happycoding.