【问题标题】:How do I access TextBox controls OUTSIDE of edit/update event?如何在编辑/更新事件之外访问 TextBox 控件?
【发布时间】:2017-11-28 01:52:44
【问题描述】:

我已尝试使用 FindControl,这是每个 StackOverflow 主题所建议的,但我得到一个对象引用错误。难道没有别的办法了吗?我发现一个话题,这个人似乎和我有同样的问题,但也没有人回答他。

我正在尝试遍历我的 GridView 并进行比较,但 row.Cells[3].Text 返回一个空白字符串。我认为这是因为我的 GridView 中有 TextBox 控件,但是当我尝试在 EDIT/UPDATE 事件之外访问 TextBox 控件时,我收到“对象引用未设置为对象实例”错误。对我来说,我得到这个错误是有道理的,因为在我循环遍历 GridView 时 TextBox 没有“打开”。

所以这是我的困境。我无法以普通方式(row.Cells[3].Text)获取值,而且我似乎也无法通过使用 FindControl 来获取它。

在这种情况下,我应该通过其他方式检索该值吗?

foreach (GridViewRow row in GridView1.Rows)
{
    if (row.Cells[3].Text == storeNumber)
    {
        // blah blah
    }
}

或者,

foreach (GridViewRow row in GridView1.Rows)
{
    if (row.FindControl("StoreNumberLabel").ToString() == storeNumber)
    {
        // blah blah
    }
}

我也尝试将 row.FindControl 转换为 TextBox 并使用 .Text 而不是 .ToString(),但结果相同。

我已经阅读了无数关于相关情况的 StackOverflow 问题,但我找不到与我的具体问题相关的任何内容。如果有一个主题已经解决了这个问题,请链接我。我到处寻找解决方案,但找不到任何东西。

更新:这是我的 aspx 代码

<asp:TemplateField HeaderText="Store">
    <ItemTemplate>
        <asp:Label ID="StoreNumberLabel" runat="server" Text='<%# Eval("Store") %>'>
        </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="storeNumberTB" runat="server" Text=' <%# Eval("Store")%>'></asp:TextBox>
    </EditItemTemplate>
</asp:TemplateField>

更新2

我已经搞定了。诀窍是检查 row.FindControl("yourControl") 是否为空。不是 TextBox 的 .Text,而只是 row.FindControl()。

现在的问题是它似乎并没有查看每一行。只有某些(我猜出于某种原因不为空的那些?)。

【问题讨论】:

  • 可以分享gridview的html代码吗?
  • 是的,请查看更新。

标签: c# asp.net gridview


【解决方案1】:

您的代码有一些问题...

首先,row.Cells[3].Text 将始终为空,因为它包含一个标签,而不是文本。

其次,您在FindControl 上使用ToString(),甚至没有将其转换回原来的类型。因此,您将storeNumberLabel 进行比较的值将是Label

第三,你在使用ToString()之前没有检查StoreNumberLabel是否存在,如果没有找到就会触发引用错误。

四,您可能期望StoreNumberLabel 存在于每一行中,但如果设置了EditIndex,则它不存在因此例外。 storeNumberTB 也是如此,仅在设置了 EditIndex 时才存在,并且仅在该行中存在。

所以你需要这样做。检查 null 并将控件转换回 Label。

if (row.FindControl("StoreNumberLabel") != null)
{
    Label lbl = row.FindControl("StoreNumberLabel") as Label;

    if (lbl.Text = storeNumber)
    {
        // blah blah
    }
}

【讨论】:

    【解决方案2】:

    你试过了吗?

    GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
    TextBox TextBox1 = row.FindControl("storeNumberTB") as TextBox; 
    string storeNumberTBtext= TextBox1.Text;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 2010-10-04
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多