asp. net USES the NamingContainer attribute to get the GridView line number

  • 2020-06-19 10:06:45
  • OfStack

Because DropDoweList is different from button, its CommandName cannot be specified, so there is no way to capture the index of the row in a regular way. After some difficulty, I found the NamingContainer attribute to solve the problem.
Let's start with Microsoft's explanation of this property:
----------------------------------
Gets a reference to the named container of the server control, which creates a 1-only namespace to distinguish server controls with the same value of the Control.ID property.
Each page of the ES11en.NET Web application contains a hierarchy of controls. This hierarchy is independent of whether the control generates UI that is visible to the user. The named container for a given control is the parent control above the control in the hierarchy that implements the INamingContainer interface. The server control that implements this interface creates a unique namespace of 1 for the ID property value of its child server controls.
When data binding is applied to list Web server controls such as Repeater and DataList server controls, it is particularly important to create a 1-only namespace for the server controls. When multiple items in a data source create multiple instances of a server control and the server control is a child of a duplicate control, the naming container ensures that each instance of these child controls has a non-conflicting UniqueID property value. The default naming container for a page is an instance of the Page class that is generated when the page is requested.
You can use this property to determine the named container in which a particular server control resides.
----------------------------------
Especially the last sentence.
Here is a code summary of the SelectedIndexChanged event:

DropDownList ddl = (DropDownList)sender;
GridViewRow gvr = (GridViewRow)ddl.NamingContainer;
int id = int.Parse(GridView1.DataKeys[gvr.RowIndex][0].ToString());
int num = int.Parse(ddl.Text);

The first sentence is used to get the DropDownList control that triggered the event.
The second sentence takes advantage of the control's NamingContainer property to get its container, which is the GridViewRow object I want.
With this, everything else is routine, and the problem is solved.

Related articles: