对象引用未设置为对象的实例 - 我收到此错误

时间:2013-10-25 05:01:34

标签: c# asp.net

<asp:TemplateField HeaderText="Team Leader">
    <ItemTemplate>
        <asp:Label ID="gvuser_teamleader" runat="server" Text='<%# Bind("TeamLeaderID")  %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtuserteamleader" runat="server" Width="100px" Text='<%# Eval("TeamLeaderID") %>' CssClass="textboxstyle roundedcorner aligncenter gradientskyblue"></asp:TextBox>
        <asp:ListBox ID="listboxuserteamleader" runat="server" Width="110px" AutoPostBack="true" OnSelectedIndexChanged="listboxuserteamleader_SelectedIndexChanged" CssClass="textboxstyle roundedcorner aligncenter gradientskyblue"></asp:ListBox>
        <asp:DropDownExtender ID="DropDownExtender3" runat="server" TargetControlID="txtuserteamleader" DropDownControlID="listboxuserteamleader"></asp:DropDownExtender>                                    
    </EditItemTemplate>
</asp:TemplateField>

当我尝试触发所选列表框索引更改事件并尝试将列表框选定值绑定到文本框时出现此错误。两个控件都在gridview编辑项模板字段中。

我的代码:

protected void listboxuserteamleader_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in gvusers.Rows)
        {
            TextBox txtuserteamleader = (TextBox)gvusers.FindControl("txtuserteamleader");
            ListBox listboxuserteamleader = (ListBox)gvusers.FindControl("listboxuserteamleader");
            txtuserteamleader.Text = listboxuserteamleader.SelectedValue.ToString();
        }
    }

2 个答案:

答案 0 :(得分:2)

只需尝试以下代码:

protected void listboxuserteamleader_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvusers.Rows)
{
    TextBox txtuserteamleader = (TextBox)gvr.FindControl("txtuserteamleader");
    ListBox listboxuserteamleader = (ListBox)gvr.FindControl("listboxuserteamleader");
    if(txtuserteamleader !=null && listboxuserteamleader !=null)
     {
       txtuserteamleader.Text = listboxuserteamleader.SelectedValue.ToString();
     }
 }
}

其实你有什么问题:你已经为每一行创建了gridview“gvusers”的实例作为gvr ...所以在foreach中你必须使用那个实例而不是“gvusers”..你错了......

这就是全部

答案 1 :(得分:0)

try this:

protected void listboxuserteamleader_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gvusers.Rows)
    {
        TextBox txtuserteamleader = (TextBox)gvr.FindControl("txtuserteamleader");
        ListBox listboxuserteamleader = (ListBox)gvr.FindControl("listboxuserteamleader");
        txtuserteamleader.Text = listboxuserteamleader.SelectedValue.ToString();
    }
}

当您遍历GridView的行时,您必须在该行内搜索控件,因此您所犯的错误是您在整个GridView中搜索它,其中每一行都有此控件。所以你需要连续搜索它。