在listview ASP.net C#中隐藏按钮

时间:2015-01-01 15:06:22

标签: c# asp.net listview

我想隐藏列表视图中的按钮。

如果查询结果为= commandArgument,则条件为隐藏按钮。

错误信息是: -

Object reference not set to an instance of an object

- string button = Button.CommandArgument **;

这是按钮

<asp:Button ID="addFollowerButton" runat="server" Text="Add as Follower" 
 CommandArgument='<%# Eval("ProfileId") %>' OnClick="acceptRequest_Click" 
 CssClass="btn btn-info btn-xs pull-right" Width="135px" />

这是代码

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        // request Query string
        var querystring = Request.QueryString["ProjectId"];
        var Button = sender as Button;            
        string connectionString = 
       ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

       string select = "Select ProfileId from Project_Follower Where ProjectId = @ProjectId";

       using (SqlConnection myConnection = new SqlConnection(connectionString))
        {
            myConnection.Open();
            SqlCommand myCommand = new SqlCommand(select, myConnection);
            myCommand.Parameters.AddWithValue("@ProjectId", querystring);

            myCommand.ExecuteNonQuery();

            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                string button = Button.CommandArgument;
                if (myCommand.ExecuteScalar().ToString() == button)
                {
                    Button hdn = (Button)e.Item.FindControl("addFollowerButton");
                    hdn.Visible = false;
                }
            }
        }

2 个答案:

答案 0 :(得分:0)

您在代码中将sender对象转换为Button。但是,当您在ListView1_ItemDataBound - 事件处理程序中执行此操作时,sender不会是Button类型。这导致NULL赋值给var Button

稍后在您的代码中,您尝试获取CommandArgument的{​​{1}} - 属性,该实例会为您提供NullReferenceException,因为变量Button为NULL。

也许您可以从Button获取有关要隐藏的按钮的信息。看看:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewitemeventargs.item%28v=vs.110%29.aspx

答案 1 :(得分:0)

首先需要找到嵌套在ListView

中的按钮
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{

      if(e.Item == null)
         return;

      Button btn1 = (Button)e.Item.FindControl("YourButtonID");
 }

为此,您需要为按钮添加特定ID:

 <asp:Button ID="addFollowerButton" runat="server" ID="YourButtonID" Text="Add as Follower" CommandArgument='<%# Eval("ProfileId") %>' OnClick="acceptRequest_Click" CssClass="btn btn-info btn-xs pull-right" Width="135px" />

使用ItemDataBound中的按钮后,您可以执行任何操作。你可以打电话:

btn1.Visible = false;//this will make the button not visible
string cmdArgument = btn1.CommandArgument;// this will take commandArgument of the button.

修改

应为Button btn1 = (Button)e.Item.FindControl("YourButtonID");