在Gridview中设置按钮属性

时间:2017-12-11 13:48:22

标签: c# asp.net listview button gridview

我在Gridview中有一个按钮。我想要做的是单击按钮时只需更改按钮颜色。 但是,在发布分页并单击按钮后,没有任何反应。 我错过了一步。

这是我的.aspx代码

<asp:GridView   id="gvStatus" runat="server" AutoGenerateColumns="false" BorderWidth="1px" BackColor="White" CellPadding="3" CellSpacing="2" BorderStyle="Solid" BorderColor="Black" GridLines="Both" Pager="10" OnRowDataBound="setcolor" OnRowCommand="setsingle" >
        <Columns>
                <asp:TemplateField HeaderText="1"  Visible="true" HeaderStyle-CssClass= "hdrBase" ItemStyle-CssClass="GridBase">
                    <ItemTemplate>
                        <asp:Button id="btnDOne" Width="35px"  Height ="25px" runat="server" Text='<%#(Eval("dateone", "{0:ddd}"))%>' CommandName="GetData" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" ></asp:Button>
                    </ItemTemplate>
                </asp:TemplateField>        
        </Columns>
    </asp:GridView>

这是c#

        protected void setsingle(object sender, GridViewCommandEventArgs e)
    {   
        if (e.CommandName == "GetData")
            { 
                //Get row index
                int rowindex  = Convert.ToInt32(e.CommandArgument);
                ////Get Row
                GridViewRow gvr = gvStatus.Rows[rowindex];
                //Find the button
                Button DayButton = gvr.FindControl("btnDOne") as Button;    
                //Set the color of the button
                DayButton.BackColor = Color.Cyan;
            }

要测试代码是否正常工作,请向Gridview添加一个linkbutton并为其指定相同的CommandName:

            <asp:TemplateField HeaderText="1"  Visible="true" HeaderStyle-CssClass= "hdrBase" ItemStyle-CssClass="GridBase">
                <ItemTemplate>
                    <asp:Button id="btnDOne" Width="35px"  Height ="25px" runat="server" Text='<%#(Eval("dateone", "{0:ddd}"))%>' CommandName="GetData" CommandArgument='<%# Container.DataItemIndex %>' ></asp:Button>
                    <asp:LinkButton id="lbd1" runat="server"  Text="clickme " CommandName="GetData" CommandArgument='<%# Container.DataItemIndex %>'/>
                </ItemTemplate>
            </asp:TemplateField>

所以,linkbutton执行后面的代码没问题。但命令按钮不执行任何操作。在最后一段代码片段中,您会注意到我比较了两者,并且基本上使命令按钮与链接按钮匹配,直到CommandArgument为止。

我已经验证了后面代码的工作原理,以及CommandName赋值是否正确。 是否有不同的方法为命令按钮执行此操作?

1 个答案:

答案 0 :(得分:0)

我最终放弃了命令按钮并使用链接按钮,然后根据需要设置网格单元格的背景颜色。