Usage experience of DataGrid (with a lot of code)
1. Design a style for the DataGrid Control
Add the following code after <asp: datagrid id = "DataGrid1" runat = "server">
<FooterStyle ForeColor = "Black" BackColor = "# CCCCCC"> </FooterStyle>
<SelectedItemStyle Font-Bold = "True" ForeColor = "White" BackColor = "# 008A8C"> </SelectedItemStyle>
<AlternatingItemStyle BackColor = "Gainsboro"> </AlternatingItemStyle>
<ItemStyle ForeColor = "Black" BackColor = "# EEEEEE"> </ItemStyle>
<HeaderStyle Font-Bold = "True" ForeColor = "White" BackColor = "#000084"> </HeaderStyle>
Note:
(1) the attributes of ForeColor BackColor Font-Bold are mainly used in each tag.
2. Add binding columns for the DataGrid Control
<Asp: BoundColumn DataField = "" ReadOnly = "True" HeaderText = ""> </asp: BoundColumn>
Note:
(1) The basic attribute in the tag is DataField/HeaderText.
(2) DataFormatString is used to obtain or set the display format strings of items in the specified column.
The format is {A: Bxx }. For example, the formatted string {0: F2} displays the number of fixed points with two decimal places.
The A value can only be set to 0, because each cell has only one value.
The display format of the specified value after the colon (B in general)
C. The value is displayed in currency format.
D. The value is displayed in decimal format.
E. The value is displayed in the scientific notation (exponent) format.
F displays the value in a fixed format.
G displays the value in the regular format.
N is a numeric value.
X indicates the value in hexadecimal format.
(3) Visible gets or sets a value that indicates whether this column is Visible in the DataGrid Control.
(4) ReadOnly sets whether some columns are read-only. If they are read-only, they cannot be modified.
(5) The name of the field or expression passed to the OnSortCommand method when SortExpression gets or sets the columns to be sorted.
3. Add a template column for The DataGrid Control
<Asp: TemplateColumn HeaderText = "type">
<ItemTemplate>
<Asp: Label Text = '<% # DataBinder. Eval (Container. DataItem, "actorclassname") %> 'runat = "server" ID = "Label1"/>
</ItemTemplate>
<EditItemTemplate>
<Select name = "sltclassname">
<% = ActorClass. GetParentClass (0) %>
</Select>
</EditItemTemplate>
</Asp: TemplateColumn>
Note:
(1) the basic framework is
<Asp: TemplateColumn HeaderText = "type">
<ItemTemplate> </ItemTemplate>
</Asp: TemplateColumn>
(2) Comprehensive template Columns
<Asp: TemplateColumn>
<HeaderTemplate>
<B> Tax </B>
</HeaderTemplate>
<ItemTemplate>
<Asp: Label
Text = '<% # DataBinder. Eval (Container. DataItem, "Tax") %>'
Runat = "server"/>
</ItemTemplate>
<EditItemTemplate>
<Asp: CheckBox
Text = "Taxable"
Runat = "server"/>
</EditItemTemplate>
<FooterTemplate>
<Asp: HyperLink id = "HyperLink1"
Text = "Microsoft"
NavigateUrl = "http://www.microsoft.com"
Runat = "server"/>
</FooterTemplate>
</Asp: TemplateColumn>
(3) apply template columns for Boolean Columns
<Asp: TemplateColumn>
<ItemTemplate>
<Asp: Label
Text = '<% # DataBinder. Eval (Container. DataItem, "Tax") %>'
Runat = "server"/>
</ItemTemplate>
<EditItemTemplate>
<Asp: CheckBox
Text = "Taxable"
Runat = "server"/>
</EditItemTemplate>
</Asp: TemplateColumn>
In normal status, use the Label control to display
In the editing status, use the CheckBox control to display
(4) apply template columns for Enumeration type columns, such as business regions (all networks/Guangdong/Yunnan)
<Asp: TemplateColumn HeaderText = "Processing Method">
<ItemTemplate>
<Asp: Label ID = "lbStatus">
<% # DataBinder. Eval (Container, "DataItem. DealWith") %>
</Asp: Label>
</ItemTemplate>
<EditItemTemplate>
<Asp: DropDownList id = "dpStatus2" runat = "server" DataTextField = "status">
<Asp: ListItem Value = "Log"> Log </asp: ListItem>
<Asp: ListItem Value = "SendSms"> SendSms (SMS) </asp: ListItem>
</Asp: DropDownList>
</EditItemTemplate>
</Asp: TemplateColumn>
In normal status, use the Label control to display
In the editing status, use the DropDownList control to display
(5) It is a long string Application Template column, such as the content of an article
Not done
4. Add a button column for The DataGrid Control
<Asp: ButtonColumn
HeaderText = "Remove from cart"
ButtonType = "PushButton"
Text = "Remove"
CommandName = "RemoveFromCart"/>
(1) To use the button column, you must add the OnItemCommand attribute to the DataGrid Control and add processing methods for this event.
(2) The template column can implement any function that the button column can implement.
5. Add edit columns for the DataGrid Control
<Asp: EditCommandColumn ButtonType = "LinkButton" UpdateText = "Update" HeaderText = "edit" CancelText = "cancel" EditText = "edit"> </asp: EditCommandColumn>
(1) ButtonType has two values: the column of the LinkButton hyperlink style button and the column of the PushButton normal button.
6. Add a hyperlink column for The DataGrid Control
<Asp: HyperLinkColumn Text = "add subclass" DataNavigateUrlField = "ActorclassID" DataNavigateUrlFormatString = "addActorClass. aspx? ClassID = {0} "> </asp: HyperLinkColumn>
(1) set the same text and jump URL for each line
When the Text and NavigateUrl attributes are set, all hyperlinks in the column share the same title and URL.
(2) set different texts and URLs for each line
A. Use DataTextField to set the fields of the data source. If you want to process the fields based on the original data (for example, if the field value is 300, you want to display the fields as 300 RMB)
Then set the DataTextFormatString field.
B. Use DataNavigateUrlField and DataNavigateUrlFormatString to set the URL address.
Use DataTextField = "money" DataTextFormatString = "{0} RMB"
C. Example
DataNavigateUrlField = "ActorclassID" DataNavigateUrlFormatString = "addActorClass. aspx? ClassID = {0 }"
7. Add "edit" Code for the DataGrid Control
Add in the DataGrid label
OnUpdateCommand = "Maid Update" OnCancelCommand = "maid" OnEditCommand = "Maid edit" code
Add the following code to the codeBehind page:
/// Response edit button
Public void datagrid#edit (Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = e. Item. ItemIndex;
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by depth, orderID desc "));
}
/// Response cancel button
Public void DataGrid1_Cancel (Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex =-1;
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by depth, orderID desc "));
}
/// Response to the Update button
Public void datagrid#update (Object sender, DataGridCommandEventArgs e)
{
TextBox ClassNameText = (TextBox) e. Item. Cells [1]. Controls [0];
String className = ClassNameText. Text;
Int classID = Int32.Parse (e. Item. Cells [0]. Text). ToString ());
TextBox orderID2 = (TextBox) e. Item. Cells [5]. Controls [0];
Int orderID = Int32.Parse (orderID2.Text );
ActorClass. ModifyActorClass (className, classID, orderID );
DataGrid1.EditItemIndex =-1;
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by depth, orderID desc "));
}
Description
(1) Format of the DataGrid event handler
MethodName (Object sender, DataGridCommandEventArgs e)
(2) Description of the update button
A. Get the text box in the editing status
TextBox ClassNameText = (TextBox) e. Item. Cells [1]. Controls [0];
String className = ClassNameText. Text;
B. Obtain the drop-down list box in the editing status.
Method 1
Int classID;
ClassID = Int32.Parse (Request. Form. Get ("sltclassname "));
Method 2
DropDownList bbb = (DropDownList) e. Item. Cells [10]. FindControl ("dpStatus2 ");
String ddpValue = bbb. SelectedValue
C. Obtain the check boxes in the editing status.
Bool boolEnabled = (CheckBox) e. Item. FindControl ("chk_enabled"). Checked;
String str2;
If (boolEnabled)
{
Str2 = "1 ";
}
Else
{
Str2 = "0 ";
}
Assign a value to str2 because the Boolean value inserted to the database can only be 1 or 0.
D. Get the text value in the editing status, that is, the column is read-only.
String storyID = (e. Item. Cells [0]. Text). ToString ();
8. Add paging events for the DataGrid Control
Add the following code to the DataGrid Control label:
OnPageIndexChanged = "Maid pageindexchanged"
Add the following code to the background:
/// <Summary>
/// Response to paging events
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Public void datagrid#page (Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e. NewPageIndex;
DataBind ();
}
9. Add binding events for the DataGrid control, that is, event processing when the DataGrid is bound
Generally, some events are used for page effects, such as changing the background color and text box size.
OnItemDataBound = "maid"
/// <Summary>
/// Response to the DataGrid binding event
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Public void maid (object sender, System. Web. UI. WebControls. DataGridItemEventArgs e)
{
If (e. Item. ItemType = ListItemType. Item)
{
E. Item. Attributes. Add ("onmouseover", "this. style. backgroundColor = '# c8dafa '");
E. Item. Attributes. Add ("onmouseout", "this. style. backgroundColor = 'white '");
}
Else if (e. Item. ItemType = ListItemType. AlternatingItem)
{
E. Item. Attributes. Add ("onmouseover", "this. style. backgroundColor = '# c8dafa '");
E. Item. Attributes. Add ("onmouseout", "this. style. backgroundColor = '# f6f6f6 '");
}
}
10. Add a button for the DataGrid Control to process the event
Add the following code to the DataGrid Control label:
OnItemCommand = "ItemsGrid_Command"
Add the following code to the background:
Public void ItemsGrid_Command (Object sender, DataGridCommandEventArgs e)
{
Switch (LinkButton) e. CommandSource). CommandName)
{
Case "Delete ":
Int classID = Int32.Parse (e. Item. Cells [0]. Text). ToString ());
ActorClass. DeleteActorClass (classID );
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by depth, orderID desc "));
Break;
// Add other cases here, if there are multiple ButtonColumns in
// The DataGrid control.
Case "hidden ":
Int actorID = Int32.Parse (e. Item. Cells [0]. Text). ToString ());
ActorClass. HiddenActorClass (actorID );
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by depth, orderID desc "));
Break;
Case "MoveUp ":
Int actorclassID = Int32.Parse (e. Item. Cells [0]. Text). ToString ());
String orderID = (e. Item. Cells [5]. Text). ToString ();
ActorClass. MoveUp (orderID, actorclassID );
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by depth, orderID desc "));
Break;
Case "MoveDown ":
ActorclassID = Int32.Parse (e. Item. Cells [0]. Text). ToString ());
OrderID = (e. Item. Cells [5]. Text). ToString ();
ActorClass. MoveDown (orderID, actorclassID );
If (Request. QueryString. Get ("classID ")! = Null)
Common. bindData (maid, Common. getSource ("select * from ActorClass where parentID =" + Request. queryString. get ("classID") + "order by depth, orderID desc "));
Else
Common. BindData (maid, Common. GetSource ("select * from ActorClass where depth = 1 order by orderID "));
Break;
Default:
// Do nothing.
Break;
}
}
11. Add a template column for The DataGrid, but the content displays "Link" or text based on the field value
The following three examples show different codes for displaying content and display controls based on different field columns.
<Asp: TemplateColumn HeaderText = "sub-menu">
<ItemTemplate>
<% # ActorClassManage. hasLeaf (DataBinder. eval (Container. dataItem, "ActorClassID "). toString (), DataBinder. eval (Container. dataItem, "child "). toString () %>
</ItemTemplate>
</Asp: TemplateColumn>
Public static string hasLeaf (string id, string child)
{
String lRtn = "";
If (Int32.Parse (child)> 0)
LRtn = "<a href = 'actorclassmanage. aspx? ClassID = "+ id +" '> <font color = blue> sub-menu ("+ child +") </font> </a> ";
Else
LRtn = "no sub-menu ";
Return lRtn;
}
<Asp: TemplateColumn HeaderText = "attribute">
<ItemTemplate>
<Asp: LinkButton Text = '<% # IsHidden (DataBinder. eval (Container. dataItem, "ActorClassID "). toString (), (bool) DataBinder. eval (Container. dataItem, "Enabled") %> 'runat = "server" CommandName = "hidden" ID = "Linkbutton1"> </asp: LinkButton>
</ItemTemplate>
</Asp: TemplateColumn>
Public static string IsHidden (string id, bool enabled)
{
String lRtn = "";
If (enabled = true)
{
LRtn = "[display]";
}
Else
{
LRtn = "hide ";
}
Return lRtn;
}
Public static void Sort (string actorclassID, string orderID)
{
String temp = "";
If (Int32.Parse (BgPicManage. GetMaxCode ("actorclass", "orderID") = Int32.Parse (orderID ))
{
Temp + = "<ipnut type = 'submit 'value = 'move downward'> ";
}
If (Int32.Parse (orderID) = 0)
{
Temp + = "<ipnut type = 'submit 'value = 'move up'> ";
}
}
12. DataGrid Control custom paging code
Place the following code in the form that contains <DataGrid>,
<P style = "FONT-SIZE: 9pt" align = "center">
<Asp: label id = "lblPageCount" runat = "server"> </asp: label>
<Asp: label id = "lblCurrentIndex" runat = "server"> </asp: label>
<Asp: linkbutton id = "btnFirst" onclick = "PagerButtonClick" runat = "server" Font-Name = "verdana"
Font-size = "8pt" ForeColor = "navy" CommandArgument = "0"> </asp: linkbutton>
<Asp: linkbutton id = "btnPrev" onclick = "PagerButtonClick" runat = "server" Font-Name = "verdana"
Font-size = "8pt" ForeColor = "navy" CommandArgument = "prev"> </asp: linkbutton>
<Asp: linkbutton id = "btnNext" onclick = "PagerButtonClick" runat = "server" Font-Name = "verdana"
Font-size = "8pt" ForeColor = "navy" CommandArgument = "next"> </asp: linkbutton>
<Asp: linkbutton id = "btnLast" onclick = "PagerButtonClick" runat = "server" Font-Name = "verdana"
Font-size = "8pt" ForeColor = "navy" CommandArgument = "last"> </asp: linkbutton>
</P>
Background code
Private void Page_Load (object sender, System. EventArgs e)
{
// Place user code here to initialize the page
BtnFirst. Text = "Homepage ";
BtnPrev. Text = "Previous Page ";
BtnNext. Text = "next page ";
BtnLast. Text = "last page ";
// Bind the data source
If (! Page. IsPostBack)
{
OpenDatabase ();
BindGrid ();
}
}
// Display "page number, total * page"
Private void ShowStats ()
{
LblCurrentIndex. Text = "" + (MyDataGrid. CurrentPageIndex + 1). ToString () + "page ";
LblPageCount. Text = "Total" + MyDataGrid. PageCount. ToString () + "page ";
}
// Response pagination button
Public void PagerButtonClick (object sender, EventArgs e)
{
String arg = (LinkButton) sender). CommandArgument. ToString ();
Switch (arg)
{
Case "next ":
If (MyDataGrid. CurrentPageIndex <(MyDataGrid. PageCount-1 ))
{
MyDataGrid. CurrentPageIndex + = 1;
}
Break;
Case "prev ":
If (MyDataGrid. CurrentPageIndex> 0)
{
MyDataGrid. CurrentPageIndex-= 1;
}
Break;
Case "last ":
MyDataGrid. CurrentPageIndex = (MyDataGrid. PageCount-1 );
Break;
Default:
MyDataGrid. CurrentPageIndex = System. Convert. ToInt32 (arg );
Break;
}
BindGrid ();
ShowStats ();
}