Because DropDoweList is different from button, you cannot specify its CommandName. Therefore, you cannot capture the index of the row in a conventional way. After some twists and turns, I found the NamingContainer attribute to solve the problem.
Let's take a look at Microsoft's explanation of this attribute:
----------------------------------
Gets a reference to the name container of the server Control. This reference creates a unique namespace to distinguish the server Control with the same Control. ID attribute value.
Each page of an ASP. NET Web application contains a control hierarchy. This hierarchy is irrelevant to whether the control generates a user-visible UI. The name container of the given control is the parent control on the control in the hierarchy. This parent control implements the INamingContainer interface. The server control that implements this interface creates a unique namespace for the ID attribute value of its subserver control.
When you bind data to a list Web server control (such as a Repeater and DataList Server Control), it is particularly important to create a unique namespace for the server control. When multiple items in the data source create multiple instances of the server control and the server control is a child level of the repeated control, the naming container ensures that each instance of these child controls has a UniqueID attribute value that does not conflict with each other. The default naming container of the Page is the Page class instance generated when the Page is requested.
You can use this property to determine the name container of a specific server control.
----------------------------------
In particular, the last sentence.
The following is the code summary of the SelectedIndexChanged event:
Copy codeThe Code is as follows:
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 obtain the DropDownList control that triggers the event.
The second sentence is to use the NamingContainer attribute of the control to obtain its container, which is also the GridViewRow object I want.
With this, the rest are common usage and the problem can be solved.