如何对一组动态单选按钮应用需求字段验证

时间:2011-12-08 04:51:01

标签: c# asp.net dynamic radio-button customvalidator

我在asp:table控件中动态创建一组单选按钮。

例如: Qst1

RB1​​
RB2
RB2

Qyst2

RB1​​
RB2
RB2

需要:

用户应为每个问题选择答案。我计划使用自定义验证器。请任何人指导我

代码:

        RadioButton radioButton = new RadioButton();

        radioButton.ID = id;
        radioButton.ToolTip = text;
        radioButton.Attributes.Add(ID_TEXT, id);
        radioButton.GroupName = categoryID + QUESTIONS;
        radioButton.EnableViewState = true;
        radioButton.AutoPostBack = false;
        radioButton.Checked = isSelected;

        TableCell cell = new TableCell();
        cell.Controls.Add(radioButton);

        TableRow row = new TableRow();
        row.Height = 20;
        row.Cells.Add(cell);

        table.Rows.Add(row);

更新

我使用Custome验证器获得解决方案:

代码:

protected void ValidateSample(object source, ServerValidateEventArgs args)
    {
        RadioButton rb = new RadioButton();
        string rbGroupName = string.Empty;
        bool valid = false;
        bool groupSelection = false;

        foreach (TableRow tr in QuestionTable.Controls)
        {

            foreach (TableCell tc in tr.Controls)
            {
                if (tc.Controls[0] is Label)
                {
                    if (QuestionTable.Rows.GetRowIndex(tr) + 1 <= QuestionTable.Rows.Count)
                    {
                        rb = (RadioButton)
                            QuestionTable.Rows[QuestionTable.Rows.GetRowIndex(tr) + 1]
                            .Cells[0].Controls[0];
                        if (rb != null)
                        {
                            rbGroupName = rb.GroupName;
                            valid = groupSelection;
                            groupSelection = false;
                        }
                    }
                    break;
                }

                if (tc.Controls[0] is RadioButton)
                {
                    rb = (RadioButton)tc.Controls[0];
                    if (rb.GroupName.Equals(rbGroupName))
                    {
                        if (rb.Checked)
                        {
                            groupSelection = true;
                        }
                    }

                    break;
                }
            }
        }

        args.IsValid = valid;
    }

<asp:CustomValidator ID="CustomValidator1" runat="server" class="LabelErrorStyle" Text="*" ErrorMessage="Please select one of the radio button" OnServerValidate="ValidateSample" ValidateEmptyText="true"
Display="Dynamic" >*</asp:CustomValidator>

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式动态添加验证,您必须确保根据radiobutton组进行不同的验证

 RequiredFieldValidator rqdVal = new RequiredFieldValidator(); 
    rqdVal.ID = "rqdVal" + i.ToString(); 
    rqdVal.ControlToValidate = "id"; 
    rqdVal.ErrorMessage = "Please enter a value"; 
    rqdVal.Display =ValidatorDisplay.Dynamic; 

了解更多信息,请查看this link