views:

148

answers:

2

Background

I have a GridView where input in Column1 depends on the input Column2.

  • If a user enters a N in Column2 the system will put a Y in Column1.

The Validatons are implemented using Regexs and Custom validation. I would prefer a validation solution that doesn't use JavaScript.

|Column1| Column2|
__________________
| Y     | N
__________________
|N      | Y
__________________
|N      | N

Question

How can I validate these entries in the Gridview without using JavaScript?

+3  A: 

Why not use two radio buttons?

<asp:templatefield>
  <itemtemplate>
    <asp:radiobutton id="rbYes" runat="server" groupname="YesNo" text="Yes" />
    <asp:radiobutton id="rbNo" runat="server" groupname="YesNo" text="No" />
  </itemtemplate>
</asp:templatefield>
Michael M
+1  A: 

You could use radio buttons and the 'Template' column feature of a GridView. The GridView markup would look like this:

    <asp:GridView ID="gvTest" runat="server" AutoGenerateColumns="false" 
        OnRowDataBound="gvTest_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Column 1">
                <ItemTemplate>
                    <asp:RadioButton ID="rbSelect1" runat="server" Text="" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Column 2">
                <ItemTemplate>
                    <asp:RadioButton ID="rbSelect2" runat="server" Text="" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

The trick then would be to correctly set the 'GroupName' property of each radio button so that each row of the resulting grid is treated as a single radio button group by the browser. That's where the 'OnRowDataBound' handler specified on the grid comes into play. The definition of the 'gvTest_RowDataBound' handler method could be something like:

protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        RadioButton rb1 = (RadioButton)e.Row.FindControl("rbSelect1");
        RadioButton rb2 = (RadioButton)e.Row.FindControl("rbSelect2");
        rb1.GroupName = rb2.GroupName = string.Format("Select_{0}", e.Row.RowIndex);
    }
}

By appending the row index to the group name to both of the radio buttons in each row you're going to ensure that the browser will treat them as a group and only allow the selection of one value per row. The result would look something like this:

GridView screenshot

Jesse Taber