Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

asp.net - Change button text in asp:gridview based on cell value C#

I’m trying to pass a cell value from a gridview to my code behind. Ultimately, I need to change the text of a button depending on the cell value.

Here is the code I have:

My .aspx page:

<asp:UpdatePanel ID="UpdatePanel2" runat="server">
  <ContentTemplate>
    <asp:GridView ID="gridView1" runat="server" OnRowCommand="gview_RowCommand" AutoGenerateColumns="False">
        <Columns>
             <asp:TemplateField HeaderText="Active Status">
                <ItemTemplate>
                    <asp:Label ID="Active" runat="server" Text='<%# Eval("IsActive") %>'></asp:Label>
                    <asp:Button runat="server" ID="buttonChangeActiveStatus" CommandName="<%# Eval("IsActive") %>" CommandArgument="<%# Eval("IsActive") %>" onclick="buttonChangeActiveStatus_Click" text=""/>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
     </asp:GridView>
</ContentTemplate>

And my .cs code behind:

protected void gview_RowCommand(Object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i <= gridView1.Rows.Count - 1; i++)
        {
            Button activeButton = (Button)gridView1.Rows[i].FindControl("buttonChangeActiveStatus");


           // if (cellValue = true)
           // {
                //change button text foo
           // }
           // else
           // {
           //     //change button text to bar
           // }    
        }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Figured it out. here's what i added to my code-behind:

  protected void RowDataBound(Object sender, GridViewRowEventArgs e)
    {

        for (int i = 0; i <= gridView.Rows.Count - 1; i++)
        {
            Button activeButton = (Button)gridViewTenantDetails.Rows[i].FindControl("buttonChangeActiveStatus");

            string cellValue = activeButton.CommandArgument.ToString();
            if (cellValue == "True")
            {
                activeButton.Text = "foo";

            }

            else
            {
                activeButton.Text = "bar";
            }
        }   
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...