Liev04
Liev04

Reputation: 441

Radio Button doesn't work inside my GridView

I have a GridView. Every row has a textbox and a radiobutton (3 options)

If the radiobutton is selected then the textbox.text = ""

Problem: when OnSelectedIndexChanged is called every textbox inside my grid goes blank

How can I clear only the textbox of the row I selected the radiobutton in?

ASPX markup

<asp:GridView id="mygrid" Runat="server">
   <Columns>            
       <asp:TemplateField>
           <ItemTemplate>
               <asp:RadioButtonList ID="hi" runat="server" 
                    OnSelectedIndexChanged="zzz" AutoPostBack="true" />
               <asp:TextBox ID="txPregoeiro" runat="server" Text="." />
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>

C# code-behind

protected void zzz(object sender, EventArgs e)
{
    foreach (GridViewRow _row in mygrid.Rows)
    {
        if (_row.RowType == DataControlRowType.DataRow)
        {
            RadioButtonList hi = (RadioButtonList)_row.FindControl("hi");
            TextBox txPregoeiro = (TextBox)_row.FindControl("txPregoeiro");
            txPregoeiro.Text = string.Empty;
        }
    }
}

Upvotes: 0

Views: 274

Answers (2)

John Paul
John Paul

Reputation: 837

Your not checking to see if the radio button list has a selected item or not. As a result you are always setting the textbox text to blank. Change the function to:

    GridViewRow _row = mygrid.SelectedRow;
    if (_row.RowType == DataControlRowType.DataRow)
    {
        RadioButtonList hi = (RadioButtonList)_row.FindControl("hi");
        if(hi.SelectedItem != null) //This checks to see if a radio button in the list was selected
        {
            TextBox txPregoeiro = (TextBox)_row.FindControl("txPregoeiro");
            txPregoeiro.Text = string.Empty;
        }   
    }

Upvotes: 2

Stephen Brickner
Stephen Brickner

Reputation: 2602

You are currently doing it for every row which will clear every text box. Give this a try.

 protected void zzz(object sender, EventArgs e)
    {
        var caller = (RadionButtonList)sender;

        foreach (GridViewRow _row in mygrid.Rows)
        {
            if (_row.RowType == DataControlRowType.DataRow)
            {
                RadioButtonList hi = (RadioButtonList)_row.FindControl("hi");

                if(hi == caller) 
                {
                  TextBox txPregoeiro = (TextBox)_row.FindControl("txPregoeiro");
                  txPregoeiro.Text = string.Empty;
                  break; //a match was found break from the loop
                }
            }
        }
    }

Upvotes: 1

Related Questions