Events programmed by the GridView Control

Source: Internet
Author: User
I put forward all the MSDN examples one by one. This makes it easier to understand.

PageIndexChanged
When you click a page navigation button, it occurs after the GridView control handles paging operations. This event is usually used in the following scenarios: After you locate another page in the control, you need to execute a task.

PageIndexChanging
When you click a page navigation button, it occurs before the GridView control handles paging operations. This event is usually used to cancel the paging operation.

RowCancelingEdit
When you click the cancel button for a row, it occurs before the GridView control exits the editing mode. This event is usually used to stop the cancellation operation.

RowCommand
It occurs when you click the button in the GridView control. This event is usually used to execute a task when you click a button in the control.

RowCreated
This occurs when a new row is created in the GridView control. This event is usually used to modify the content of a row when a row is created.

RowDataBound
When the data row is bound to the data in the GridView control. This event is usually used to modify the content of a row when the row is bound to Data.

RowDeleted
When you click the "delete" button for a row, it occurs after the GridView control deletes the corresponding record from the data source. This event is usually used to check the results of the delete operation.

RowDeleting
When you click the delete button for a row, it occurs before the GridView control deletes the corresponding record from the data source. This event is usually used to cancel the delete operation.

RowEditing
After you click the "edit" button for a row, the GridView control enters the editing mode. This event is usually used to cancel the edit operation.

RowUpdated
This occurs after you click the "Update" button for a row and the GridView control updates the row. This event is usually used to check the results of the update operation.

RowUpdating
After you click the "Update" button for a row, the GridView control updates the row. This event is usually used to cancel the update operation.

SelectedIndexChanged
After you click the "select" button for a row, the GridView control processes the selection operation. This event is usually used to execute a task after a row is selected in the control.

SelectedIndexChanging
After you click the "select" button for a row, the GridView control processes the selection operation. This event is usually used to cancel the selection operation.

Sorted
When you click a hyperlink used for column sorting, it occurs after the GridView control processes the corresponding sorting operation. This event is usually used to execute a task after you click the hyperlink used for column sorting.

Sorting
When you click a hyperlink used for column sorting, it occurs before the GridView control processes the corresponding sorting operation. This event is usually used to cancel a sorting operation or to execute a custom sorting routine.

1. PageIndexChanged event

The following code example shows how to use the PageIndexChanged event to display the Page number selected by the user from the Page Navigation Line <% @ Page language = "C #" %>
<Script runat = "server">
 
Void CustomersGridView_DataBound (Object sender, EventArgs e)
{
If (! IsPostBack)
{
DisplayCurrentPage ();
}
}

Void CustomersGridView_PageIndexChanged (Object sender, EventArgs e)
{
DisplayCurrentPage ();
}

Void DisplayCurrentPage ()
{
Int currentPage = CustomersGridView. PageIndex + 1;
Message. Text = "Page" + currentPage. ToString () + "of" +
CustomersGridView. PageCount. ToString () + ".";
}
</Script>
<Html>
<Body>
<Form id = "Form1" runat = "server">
<H3> GridView PageIndexChanged Example  
<Asp: label id = "Message"
Forecolor = "Red"
Runat = "server"/>
 
<Br/>

<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSource"
Autogeneratecolumns = "true"
Emptydatatext = "No data available ."
Allowpaging = "true"
Ondatabound = "CustomersGridView_DataBound"
Onpageindexchanged = "CustomersGridView_PageIndexChanged"
Runat = "server">
 
<Pagersettings mode = "Numeric"
Position = "Bottom"
Pagebuttoncount = "10"/>
 
<Pagerstyle backcolor = "LightBlue"/>
 
</Asp: gridview>
<Asp: sqldatasource id = "CustomersSource"
Selectcommand = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [MERs]"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server"/>
 
</Form>
</Body>
</Html>

2. PageIndexChanging event

The following code example shows how to use the PageIndexChanging event to cancel the paging operation if you try to navigate to another Page when the GridView control is in editing mode. <% @ Page language = "C #" %>

<Script runat = "server">

Void CustomersGridView_PageIndexChanging (Object sender, GridViewPageEventArgs e)
{
 
// Cancel the paging operation if the user attempts to navigate
// To another page while the GridView control is in edit mode.
If (CustomersGridView. EditIndex! =-1)
{
// Use the Cancel property to cancel the paging operation.
E. Cancel = true;
 
// Display an error message.
Int newPageNumber = e. NewPageIndex + 1;
Message. Text = "Please update the record before moving to page" +
NewPageNumber. ToString () + ".";
}
Else
{
// Clear the error message.
Message. Text = "";
}
 
}

Void CustomersGridView_RowCancelingEdit (Object sender, GridViewCancelEditEventArgs e)
{
// Clear the error message.
Message. Text = "";
}

</Script>

<Html>
<Body>
<Form id = "Form1" runat = "server">
 
<H3> GridView PageIndexChanging Example  
<Asp: label id = "Message"
Forecolor = "Red"
Runat = "server"/>
 
<Br/>

<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSource"
Autogeneratecolumns = "true"
Emptydatatext = "No data available ."
Allowpaging = "true"
Autogenerateeditbutton = "true"
Datakeynames = "CustomerID"
Onpageindexchanging = "CustomersGridView_PageIndexChanging"
Onrowcancelingedit = "CustomersGridView_RowCancelingEdit"
Runat = "server">
 
<Pagersettings mode = "Numeric"
Position = "Bottom"
Pagebuttoncount = "10"/>
 
<Pagerstyle backcolor = "LightBlue"/>
 
</Asp: gridview>
 
<! -- This example uses Microsoft SQL Server and connects -->
<! -- To the Northwind sample database. Use an ASP. NET -->
<! -- Expression to retrieve the connection string value -->
<! -- From the Web. config file. -->
<Asp: sqldatasource id = "CustomersSource"
Selectcommand = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [MERs]"
Updatecommand = "Update Customers SET CompanyName = @ CompanyName, Address = @ Address, City = @ City, PostalCode = @ PostalCode, Country = @ Country WHERE (CustomerID = @ CustomerID )"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server"/>
 
</Form>
</Body>
</Html>

The red letter is displayed when the page is in the update status and is not updated.

3. When the RowCancelingEdit event is clicked, the "cancel" button of a row in edit mode occurs before the row exits edit mode.

The following code example shows how to use the RowCancelingEdit event to display the Cancel message when you cancel the update operation of the GridView control. <% @ Page language = "C #" %>

<Script runat = "server">

Void CustomersGridView_RowCancelingEdit (Object sender, GridViewCancelEditEventArgs e)
{
 
GridViewRow row = CustomersGridView. Rows [e. RowIndex];
Message. Text = "Update for item" + row. Cells [1]. Text + "Canceled .";
 
}

</Script>

<Html>
<Body>
<Form id = "Form1" runat = "server">
 
<H3> GridView RowCancelingEdit Example  
<Asp: label id = "Message"
Forecolor = "Red"
Runat = "server"/>
 
<Br/>
<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSqlDataSource"
Autogeneratecolumns = "true"
Autogenerateeditbutton = "true"
Allowpaging = "true"
Datakeynames = "CustomerID"
Onrowcancelingedit = "CustomersGridView_RowCancelingEdit"
Runat = "server">
</Asp: gridview>
<Asp: sqldatasource id = "CustomersSqlDataSource"
Selectcommand = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [MERs]"
Updatecommand = "Update Customers SET CompanyName = @ CompanyName, Address = @ Address, City = @ City, PostalCode = @ PostalCode, Country = @ Country WHERE (CustomerID = @ CustomerID )"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server">
</Asp: sqldatasource>
 
</Form>
</Body>
</Html>

The red letter is displayed after you click the cancel button.

4. When the RowCommand event clicks a button in the GridView control, the RowCommand event is triggered.

The following example shows how to use the GridViewCommandEventArgs object that is passed to the Event Processing Method to Determine the command name of the button that triggers the event <% @ Page language = "C #" %>

<Script runat = "server">

Void CustomersGridView_RowCommand (Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use
// CommandName property to determine which button was clicked.
If (e. CommandName = "Add ")
{
// Convert the row index stored in the CommandArgument
// Property to an Integer.
Int index = Convert. ToInt32 (e. CommandArgument );
 
// Retrieve the row that contains the button clicked
// By the user from the Rows collection.
GridViewRow row = CustomersGridView. Rows [index];
 
// Create a new ListItem object for the customer in the row.
ListItem item = new ListItem ();
Item. Text = Server. HtmlDecode (row. Cells [2]. Text );
 
// If the customer is not already in the ListBox, add the ListItem
// Object to the Items collection of the ListBox control.
If (! CustomersListBox. Items. Contains (item ))
{
CustomersListBox. Items. Add (item );
}
}
}

Void CustomersGridView_RowCreated (Object sender, GridViewRowEventArgs e)
{
 
// The GridViewCommandEventArgs class does not contain
// Property that indicates which row's command button was
// Clicked. To identify which row's button was clicked, use
// The button's CommandArgument property by setting it to
// Row's index.
If (e. Row. RowType = DataControlRowType. DataRow)
{
// Retrieve the LinkButton control from the first column.
LinkButton addButton = (LinkButton) e. Row. Cells [0]. Controls [0];
 
// Set the LinkButton's CommandArgument property with
// Row's index.
AddButton. CommandArgument = e. Row. RowIndex. ToString ();
}

}
 
</Script>

<Html>
<Body>
<Form id = "Form1" runat = "server">
 
<H3> GridView RowCommand Example  
& Lt; table width = "100%" & gt;
<Tr>
& Lt; td width = "50%" & gt;
 
<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSource"
Allowpaging = "true"
Autogeneratecolumns = "false"
Onrowcommand = "CustomersGridView_RowCommand"
Onrowcreated = "CustomersGridView_RowCreated"
Runat = "server">
 
<Columns>
<Asp: buttonfield buttontype = "Link"
Commandname = "Add"
Text = "Add"/>
<Asp: boundfield datafield = "CustomerID"
Headertext = "Customer ID"/>
<Asp: boundfield datafield = "CompanyName"
Headertext = "Company Name"/>
<Asp: boundfield datafield = "City"
Headertext = "City"/>
</Columns>
 
</Asp: gridview>
 
</Td>
 
& Lt; td valign = "top" width = "50%" & gt;
 
MERs: <br/>
<Asp: listbox id = "CustomersListBox"
Runat = "server"/>
 
</Td>
</Tr>
</Table>
 
<! -- This example uses Microsoft SQL Server and connects -->
<! -- To the Northwind sample database. Use an ASP. NET -->
<! -- Expression to retrieve the connection string value -->
<! -- From the Web. config file. -->
<Asp: sqldatasource id = "CustomersSource"
Selectcommand = "Select [mermerid], [CompanyName], [City] From [MERs]"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server"/>
 
</Form>
</Body>
</Html>

5. The RowCreated event is the same as the preceding one.

6. The RowDataBound event occurs when the data row is bound to the data in the GridView control.

The following code example demonstrates how to use the RowDataBound event to modify the field value in the data source before displaying it in the GridView Control <% @ Page language = "C #" %>

<Script runat = "server">

Void CustomersGridView_RowDataBound (Object sender, GridViewRowEventArgs e)
{
 
If (e. Row. RowType = DataControlRowType. DataRow)
{
// Display the company name in italics.
E. Row. Cells [1]. Text = "<I>" + e. Row. Cells [1]. Text + "</I> ";
 
}
 
}

</Script>

<Html>
<Body>
<Form runat = "server">
 
<H3> GridView RowDataBound Example

<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSqlDataSource"
Autogeneratecolumns = "true"
Allowpaging = "true"
Onrowdatabound = "CustomersGridView_RowDataBound"
Runat = "server">
</Asp: gridview>
 
<! -- This example uses Microsoft SQL Server and connects -->
<! -- To the Northwind sample database. Use an ASP. NET -->
<! -- Expression to retrieve the connection string value -->
<! -- From the Web. config file. -->
<Asp: sqldatasource id = "CustomersSqlDataSource"
Selectcommand = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [MERs]"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server">
</Asp: sqldatasource>
 
 
</Form>
</Body>
</Html>

7. When the RowDeleted event clicks the "delete" button for a row, it occurs after the GridView control deletes the row.

The following code example shows how to use the RowDeleted event to check the deletion result. A message is displayed to indicate whether the operation is successful. <% @ Page language = "C #" %>

<Script runat = "server">

Void CustomersGridView_RowDeleted (Object sender, GridViewDeletedEventArgs e)
{
 
// Display whether the delete operation succeeded.
If (e. Exception = null)
{
Message. Text = "Row deleted successfully .";
}
Else
{
Message. Text = "An error occurred while attempting to delete the row .";
E. ExceptionHandled = true;
}
 
}
 
</Script>

<Html>
<Body>
<Form id = "Form1" runat = "server">
 
<H3> GridView RowDeleted Example  
<Asp: label id = "Message"
Forecolor = "Red"
Runat = "server"/>
 
<Br/>
 
<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSqlDataSource"
Autogeneratecolumns = "true"
Autogeneratedeletebutton = "true"
Datakeynames = "CustomerID"
Onrowdeleted = "CustomersGridView_RowDeleted"
Runat = "server">
</Asp: gridview>
 
<! -- This example uses Microsoft SQL Server and connects -->
<! -- To the Northwind sample database. Use an ASP. NET -->
<! -- Expression to retrieve the connection string value -->
<! -- From the Web. config file. -->
<Asp: sqldatasource id = "CustomersSqlDataSource"
Selectcommand = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [MERs]"
Deletecommand = "Delete from MERs where CustomerID = @ CustomerID"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server">
</Asp: sqldatasource>
 
</Form>
</Body>
</Html>

8. When the RowDeleting event is clicked on the "delete" button of a row, it occurs before the GridView control deletes the row.

The following code example shows how to use the RowDeleting event to cancel the delete operation when you try to remove the last record from the GridView control. <% @ Page language = "C #" %>

<Script runat = "server">

Void CustomersGridView_RowDeleting (Object sender, GridViewDeleteEventArgs e)
{
 
// Cancel the delete operation if the user attempts to remove
// The last record from the GridView control.
If (CustomersGridView. Rows. Count <= 1)
{
 
E. Cancel = true;
Message. Text = "You must keep at least one record .";
 
}
 
}

</Script>

<Html>
<Body>
<Form runat = "server">
 
<H3> GridView RowDeleting Example  
<Asp: label id = "Message"
Forecolor = "Red"
Runat = "server"/>
 
<Br/>
 
<! -- The GridView control automatically sets the columns -->
<! -- Specified in the datakeynames property as read-only. -->
<! -- No input controls are rendered for these columns in -->
<! -- Edit mode. -->
<Asp: gridview id = "CustomersGridView"
Performanceid = "CustomersSqlDataSource"
Autogeneratecolumns = "true"
Autogeneratedeletebutton = "true"
Datakeynames = "CustomerID"
Onrowdeleting = "CustomersGridView_RowDeleting"
Runat = "server">
</Asp: gridview>
 
<! -- This example uses Microsoft SQL Server and connects -->
<! -- To the Northwind sample database. Use an ASP. NET -->
<! -- Expression to retrieve the connection string value -->
<! -- From the Web. config file. -->
<Asp: sqldatasource id = "CustomersSqlDataSource"
Selectcommand = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [MERs]"
Deletecommand = "Delete from MERs where CustomerID = @ CustomerID"
Connectionstring = "<% $ ConnectionStrings: NorthWindConnectionString %>"
Runat = "server">
</Asp: sqldatasource>
 
</Form>
</Body>
</Html>

There are also six events. We can see that the event has a special feature, with the suffix "ed" or "ing". The difference lies in the relationship between the events and their occurrence time. the following events indicate that they are the same as above and do not need to be listed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.