c# - FindControl 找不到控件

标签 c# asp.net gridview

我正在设置一个 GridView ,以便我可以选择多个事件并将它们的 EventID 添加到逗号分隔的字符串中。这将是一项订阅服务,因此我需要知道用户想要订阅哪些事件。

我使用模板字段添加了一个复选框,我可以将其用作我想要的事件项目的指示符。

所以 GridView 看起来像这样

<asp:GridView ID="GridView1" 
    runat="server" 
    AllowPaging="True" 
    AllowSorting="True" 
    AutoGenerateColumns="False" 
    DataSourceID="SqlDataSource1" 
    PageSize="15" 
    ViewStateMode="Enabled" SelectedRowStyle-BackColor="Purple">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="eventSelected" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="EventID" HeaderText="EventID" InsertVisible="False" ReadOnly="True" SortExpression="EventID" />
        <asp:BoundField DataField="EventName" HeaderText="EventName" SortExpression="EventName" />
        <asp:BoundField DataField="BaseTypeKey" HeaderText="BaseTypeKey" SortExpression="BaseTypeKey" />
        <asp:BoundField DataField="BaseTypeDesc" HeaderText="BaseTypeDesc" ReadOnly="True" SortExpression="BaseTypeDesc" />

    </Columns>
</asp:GridView>

而且信息填充得很好。

我检索所选项目的代码应该很简单,但还没有运行。

private string GetCheckedEvents()
{
    List<string> outputString = new List<string>();
    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox cb = (CheckBox)row.FindControl("eventSelected");
        if (cb != null && cb.Checked)
        {
            outputString.Add(row.FindControl("EventID").ToString());
        }
    }
    return string.Join(",", outputString);
}

虽然调试代码时,CheckBox 设置正确并进入 if 语句,但随后点击单行代码并出现

An exception of type 'System.NullReferenceException' occurred in EventEmailerConfiguration.dll but was not handled in user code

尝试在调试器提供的对象资源管理器中导航至少可以说是一个 PITA。

我没有穿越到正确的位置吗?

如何提取我需要的信息?

最佳答案

您找不到 BoundField,因为它不是真正的控件。你必须使用 row.Cells[index].Text:

outputString.Add(row.Cells[1].Text);

关于c# - FindControl 找不到控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324174/

相关文章:

asp.net - Redis 中的 Azure 缓存/DataCache 样式区域

android - 使用 XML 的特定于平板电脑的 ImageView 宽度/高度/等值?

c# - 使用 if 语句来微观管理堆栈

c# - Web API 和 HTTP 模块

c# - 访问域外的 SelfHosted WCF 服务

c# - 找到与名为 'Home' 的 Controller 匹配的多个类型。 (奇怪的错误)

c# - 如何在浏览器处理请求时禁用开始按钮

c# - 向 gridview 添加分页 asp.net

c# - 使用对象数据填充 GridView

c# - "IN"Linq 运算符