【问题标题】:dropdownlist error object reference not set to an instance of an object [duplicate]下拉列表错误对象引用未设置为对象的实例[重复]
【发布时间】:2018-03-14 22:14:26
【问题描述】:

我有一个 DropDownList,如下所示:

<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>

当我尝试在后面的代码中引用它时,键入entryLevel 无法识别它,所以我使用了以下代码:

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

每当我运行网页并选择值时,我都会收到错误消息:

对象引用未设置为对象的实例

有人知道我为什么会收到这个错误吗?

【问题讨论】:

  • 下拉菜单在项目模板内——这意味着会有很多这样的下拉菜单。您希望其中哪一个得到FindControl 结果?
  • 我想使用 FindControl 来获取下拉菜单“entryLevel”
  • 其中有很多 - gridview 中的每一行都有一个。
  • 你在哪里绑定下拉列表?在您的代码中没有看到它
  • @cred 你把服务器端代码放在哪里了?你能展示其余的代码吗?

标签: c# asp.net gridview


【解决方案1】:

您缺少 Rows GridView 类来获取确切的 DropDownList 替换以下行:

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

如果您在 RowCommand 事件中使用您的代码,那么您可以获得rowIndex,如下所示:

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

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 2013-10-19
    • 2013-07-07
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多