1

I have a DropDownList which is shown below:

<asp:GridView ID="moduleInfo" runat="server" DataSourceID="currentModules" class="table table-striped table-bordered" AutoGenerateColumns="false"  GridLines="None">
    <Columns>
       <asp:TemplateField HeaderText="module" ItemStyle-Width="30"  >
          <ItemTemplate>
            <asp:DropDownList ID="entryLevel" CssClass="form-control" runat="server">
                <asp:ListItem Text="Level 1" Value="1"></asp:ListItem>
                <asp:ListItem Text="Level 2" Value="2"></asp:ListItem>
                <asp:ListItem Text="Level 3" Value="3"></asp:ListItem>
                <asp:ListItem Text="Level 4" Value="4"></asp:ListItem>
                <asp:ListItem Text="Level 5" Value="5"></asp:ListItem>
          </asp:DropDownList>
        </ItemTemplate>
      </asp:TemplateField>

When I try to reference it in the code behind it was not recognized by typing entryLevel, so i used below code:

DropDownList ddl = (DropDownList)moduleInfo.FindControl("entryLevel");
string Level = ddl.SelectedValue;

Whenever I run the web-page and select the value, I get the error:

object reference not set to an instance of an object

Anyone know why I'm getting this error?

cred
  • 29
  • 6

1 Answers1

0

You are missing Rows class of GridView to get the exact DropDownList replace below line:

DropDownList ddl = (DropDownList)moduleInfo.Rows[rowIndex].FindControl("entryLevel");

And if you are using your code in RowCommand event then you can get rowIndex as like this:

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;