To make it more clear to your side, I made another demo. We will add a Table, HiddenField, GridView and a Button control in the markup.
ASPX:
<asp:table id="tbl1" runat="server" />
<asp:hiddenfield id="HiddenField1" runat="server" />
<asp:gridview id="GridView1" runat="server">
</asp:gridview>
<asp:button id="Button1" runat="server" onclick="Button1_Click" text="Button"/>
The table is where we generate the DropDownList based
The HiddenField is where we store the selected DropDown ID at SelectedIndexChanged event of DropDown
The GridView contains your data
The Button is where we get the value from HiddenField and display in a Message Box (alert)
Now here's the code block:
VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
BindGridView()
End If
GenerateDropDowns(GridView1.Columns.Count)
End Sub
Private Sub GenerateDropDowns(colCount As Integer)
Dim row As New TableRow()
For i As Integer = 0 To colCount - 1
Dim cell As New TableCell()
Dim ddl As New DropDownList()
ddl.ID = "ddl" + i.ToString()
ddl.Items.Add(New ListItem("PASS", "P"))
ddl.Items.Add(New ListItem("FAIL", "F"))
ddl.AutoPostBack = True
AddHandler ddl.SelectedIndexChanged, AddressOf OnSelectedIndexChanged
cell.Controls.Add(ddl)
row.Cells.Add(cell)
Next
tbl1.Rows.Add(row)
End Sub
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddl1 As DropDownList = DirectCast(sender, DropDownList)
HiddenField1.Value = ddl1.ID
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim theDropDown As String = HiddenField1.Value
If theDropDown <> String.Empty Then
Dim msgScript As String = String.Format("alert('You have selected: {0}');", theDropDown)
Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "Alert", msgScript, True)
HiddenField1.Value = String.Empty
End If
End Sub
C# Equivalent:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindGridView();
}
GenerateDropDowns(GridView1.Columns.Count);
}
private void GenerateDropDowns(int colCount) {
TableRow row = new TableRow();
for (int i = 0; i < colCount; i++) {
TableCell cell = new TableCell();
DropDownList ddl = new DropDownList();
ddl.ID = "ddl" + i.ToString();
ddl.Items.Add(new ListItem("PASS", "P"));
ddl.Items.Add(new ListItem("FAIL", "F"));
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += OnSelectedIndexChanged;
cell.Controls.Add(ddl);
row.Cells.Add(cell);
}
tbl1.Rows.Add(row);
}
protected void OnSelectedIndexChanged(object sender, EventArgs e) {
DropDownList ddl1 = (DropDownList)sender;
HiddenField1.Value = ddl1.ID;
}
protected void Button1_Click(object sender, EventArgs e) {
string theDropDown = HiddenField1.Value;
if (theDropDown != string.Empty) {
string msgScript = string.Format("alert('You have selected: {0}');", theDropDown);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", msgScript, true);
HiddenField1.Value = string.Empty;
}
}
Hope that helps and clears your confusion.