-1

:) 在 sql 中生成该基时,我希望访问标签中任何文本中的数据,但我收到此错误 Object reference not set to an instance of an object

请帮我 :(

                <asp:DataList ID="DataList1" runat="server" CellPadding="4" 
                    DataSourceID="SqlDataSource1" ForeColor="#333333">
                    <AlternatingItemStyle BackColor="White" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <ItemStyle BackColor="#3b5998" />
                    <ItemTemplate>
                        <asp:Image ID="Image2" runat="server" Height="40px" ImageUrl='<%# Eval("ProfilePicUrl") %>' Width="50px" />
                        <div class="name-holder">
                            <asp:Label ID="UserNameLabel" runat="server" Text='<%# Eval("UserName") %>' 
                                CssClass="request-name"/>
                            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" />
                            <asp:Button ID="Button2" runat="server" onclick="Button1_Click" Text="Deny" />
                        </div>
                        <br />
                    </ItemTemplate>
                    <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                </asp:DataList>
            </div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:FacebookConnectionString %>" 
                SelectCommand="SELECT FriendRequest. UserName, aspnet_Users.ProfilePicUrl FROM FriendRequest INNER JOIN aspnet_Users ON FriendRequest.UserName = aspnet_Users.UserName WHERE (FriendRequest.FriendRequest = @FriendRequest)">
                <SelectParameters>
                    <asp:ControlParameter ControlID="username" Name="FriendRequest" 
                        PropertyName="Text" />
                </SelectParameters>
            </asp:SqlDataSource>

C#:

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label UserNameLabel = (Label)DataList1.FindControl("UserNameLabel");
        con.ConnectionString = "Data Source=localhost;Initial Catalog=Facebook;Integrated Security=True";
        con.Open();
        SqlCommand cmd = new SqlCommand("UPDATE [FriendRequest] SET [Friends]=(SELECT FriendRequest FROM [FriendRequest] WHERE UserName=@UserName1) WHERE UserName=@username", con);
        cmd.Parameters.AddWithValue("@UserName", Page.User.Identity.Name);
        cmd.Parameters.AddWithValue("@UserName1", UserNameLabel.Text);
        cmd.ExecuteNonQuery(); 

        con.Close();
    }
4

2 回答 2

0

UserNameLabel为空,因为FindControl不适用于动态生成的控件(即,来自 DataList)。当 DataList 中有多行时,您希望它如何工作?

更好的方法是利用按钮的CommandArgument属性将必要的参数携带到您的事件处理程序中。MSDN 有一个关于如何使用它的示例。

于 2012-09-15T12:34:49.287 回答
0

删除 FriendRequest.UserName 中的额外空间,并在您的 sql 服务器中触发查询并检查用户名。

于 2012-09-15T12:37:17.170 回答