【问题标题】:Radio Button doesn't work inside my GridView单选按钮在我的 GridView 中不起作用
【发布时间】:2015-12-22 08:53:50
【问题描述】:

我有一个 GridView。每行都有一个文本框和一个单选按钮(3个选项)

如果单选按钮被选中,那么textbox.text = ""

问题:当OnSelectedIndexChanged 被调用时,我的网格中的每个文本框都会变为空白

如何只清除我选择单选按钮所在行的文本框?

ASPX 标记

<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# 代码隐藏

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;
        }
    }
}

【问题讨论】:

  • 向我们展示您的代码以及您尝试过的内容
  • 感谢您的关注...看看
  • 感谢 marc_s 这不是我的母语

标签: c# gridview radio-button


【解决方案1】:

您目前正在为每一行执行此操作,这将清除每个文本框。试试这个。

 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
                }
            }
        }
    }

【讨论】:

  • 谢谢,很有帮助
  • 没问题。尽管您应该注意,但您选择的答案存在一个小问题。这样做,无论单击哪个控件,您都将发送一个事件,并更新网格中的每个文本框,无论选择了哪个单选按钮列表。这与在顶部有一个按钮循环通过网格并检查以查看哪些被选中然后清除文本框相同。获取调用者只会影响您所在的行(您在选择时唯一关心的行)。注意:添加了一个休息。
  • 好消息@StephenBrickner。我更新了我的答案,因此它首先获取选定的行,然后清除文本框。这是你根本不做任何循环来找到选定的行。
  • @John Paul,SelectedRow 有效地执行了相同的枚举,但它更简洁,做得很好。 +1
【解决方案2】:

您没有检查单选按钮列表是否有选定的项目。因此,您总是将文本框文本设置为空白。将函数改为:

    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;
        }   
    }

【讨论】:

  • 谢谢,很有帮助
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 2017-07-13
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
相关资源
最近更新 更多