动态指定RangeValidator的值

Validators in a DataGrid
By Doug Seven
Published: 6/4/2002
Reader Level: Beginner
Rated: 5.00 by 3 member(s).
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

<script language="JavaScript" type="text/javascript"> var axel = Math.random(); var num = axel * 100000000000000000 + "?"; NS4 = document.layers ;if (NS4) {origWidth = innerWidth;origHeight = innerHeight;} function reDo() {if (innerWidth != origWidth || innerHeight != origHeight) location.reload();} if (NS4) onresize = reDo; </script> <script language="Javascript1.1" type="text/javascript"> document.write(''); </script>

The Question:

I'm reading and testing your examples of validators, but I'd like to insert a RangeValidator control in a DataGrid control using range values from database... How can I do that???

The Answer:

This may be easier than you think. Since the validator control expose properties like any other Web server control, you can set those properties either declaritively or programmatically. In other words, you can set the properties inline in the control tag, or in code. For this example I'll show you how to use the DataGrid EditItemTemplate (from the TemplateColumn) and place a number of validators with their validation properties set either declaratively or programmatically.

The code for this tutorial is available in both C# and Visual Basic .NET.

Adding Ranges to Northwind

To begin with I need to add a table to the Northwind database - the Ranges table. I am going to be building an editable DataGrid that shows the Products from the Northwind database, and the Ranges table will be used to specify the minimum and maximum ranges for the ReorderLevel field in the Products table. Figure 1 shows the Ranges table structure and the data in it.

Figure 1 - The Ranges Table

The Ranges table provides minimum and maximum Reorder Levels for each category of products in the Northwind database.

Building the EditItemTemplate

I am not going to go into how to build a DataGrid with an EditItemTemplate - for a tutorial on that topic, see Working with DataGrid Templates. Rather, I will just jump right into how I have cinstructed the ItemTemplate and the EditItemTemplate.

Listing 1 shows the Template column for my DataGrid. In the ItemTemplate I render the Product information, such as the Quantitty Per Unit, Unit Price, Units In Stock, Units On Order, and Reorder Level. In the EditItemTemplate I use TextBox controls to render the values of each database field. This enables the user to change the data.

Listing 1

<asp:TemplateColumn HeaderText="Product Info">
 <ItemTemplate>
  <b>Quantity/Unit</b>
  <%# DataBinder.Eval(Container.DataItem, "QuantityPerUnit") %>
  <br>
  <b>Unit Price:</b>
  <%# DataBinder.Eval(Container.DataItem, "UnitPrice", "{0:c}") %>
  <br>
  <b>Units in Stock:</b>
  <%# DataBinder.Eval(Container.DataItem, "UnitsInStock") %>
  <br>
  <b>Units on Order:</b>
  <%# DataBinder.Eval(Container.DataItem, "UnitsOnOrder") %>
  <br>
  <b>Reorder Level:</b>
  <%# DataBinder.Eval(Container.DataItem, "ReorderLevel") %>
 </ItemTemplate>
 <EditItemTemplate>
  <table border="0" cellpadding="2" cellspacing="0">
   <tr>
    <td><b>Quantity/Unit</b></td>
    <td>
     <asp:TextBox Runat="server" ID="txtQuantityPerUnit" CssClass="NormalTextbox"
      Text='<%# DataBinder.Eval(Container.DataItem, "QuantityPerUnit") %>' /></td>
   </tr>
   <tr>
    <td><b>Unit Price:</b></td>
    <td>
     <asp:TextBox Runat="server" ID="txtUnitPrice" CssClass="NormalTextbox"
      Text='<%# DataBinder.Eval(Container.DataItem, "UnitPrice") %>' />
     <asp:RangeValidator Runat="server" ControlToValidate="txtUnitPrice"
      MinimumValue="1" MaximumValue="100" Type="Integer" Display="Dynamic">
       Unit Price must be between 1 and 100.
     </asp:RangeValidator>
     <asp:CompareValidator Runat="server" ControlToValidate="txtUnitPrice"
      Type="Double" Operator="DataTypeCheck" Display="Dynamic">
       Reorder Level must be a valid monetary value.
     </asp:CompareValidator>
     <asp:RequiredFieldValidator Runat="server" ControlToValidate="txtUnitPrice"
      Display="Dynamic">
       Reorder Level is required.
     </asp:RequiredFieldValidator>
    </td>
   </tr>
   <tr>
    <td><b>Units in Stock:</b></td>
    <td>
     <asp:TextBox Runat="server" ID="txtUnitsInStock" CssClass="NormalTextbox"
      Text='<%# DataBinder.Eval(Container.DataItem, "UnitsInStock") %>' /></td>
   </tr>
   <tr>
    <td><b>Units on Order:</b></td>
    <td>
     <asp:TextBox Runat="server" ID="txtUnitsOnOrder" CssClass="NormalTextbox"
      Text='<%# DataBinder.Eval(Container.DataItem, "UnitsOnOrder") %>' /></td>
   </tr>
   <tr>
    <td><b>Reorder Level:</b></td>
    <td>
     <asp:TextBox Runat="server" ID="txtReorderLevel" CssClass="NormalTextbox"
      Text='<%# DataBinder.Eval(Container.DataItem, "ReorderLevel") %>' />
     <asp:RangeValidator Runat="server" ControlToValidate="txtReorderLevel"
      MinimumValue='<%# DataBinder.Eval(Container.DataItem, "MinValue") %>'
      MaximumValue='<%# DataBinder.Eval(Container.DataItem, "MaxValue") %>'
      Type="Integer" Display="Dynamic">
       Reorder Level must be between <%# DataBinder.Eval(Container.DataItem, "MinValue") %>
       and <%# DataBinder.Eval(Container.DataItem, "MaxValue") %>.
     </asp:RangeValidator>
     <asp:CompareValidator Runat="server" ControlToValidate="txtReorderLevel"
      Type="Integer" Operator="DataTypeCheck" Display="Dynamic">
       Reorder Level must be a whole number.
     </asp:CompareValidator>
     <asp:RequiredFieldValidator Runat="server" ControlToValidate="txtReorderLevel"
      Display="Dynamic">
       Reorder Level is required.
     </asp:RequiredFieldValidator>
    </td>
   </tr>
  </table>
 </EditItemTemplate>
</asp:TemplateColumn>

For the UnitPrice and ReorderLevel fields I have added three validator controls, a RangeValidator, CompareValidator and RequiredFieldValidator. Combined these validators are used to ensure that a value is entered in the TextBox and that the value is numeric and within a specified range. For the UnitPrice TextBox (txtUnitPrice) the RangeValidator is set to validate within the range 1-100.

The ReorderLevel RangeValidator's properties are set based on values in the Ranges table. Listing 2 shows the BindData() method in the Web Form codebehind class, which includes the SQL SELECT command that brings the data to the DataGrid.

Private Sub BindData()

  Dim _sql As New System.Text.StringBuilder()
  _sql.Append("SELECT Products.ProductID, Products.ProductName, ")
  _sql.Append("Products.QuantityPerUnit, Products.UnitPrice, ")
  _sql.Append("Products.UnitsInStock, Products.UnitsOnOrder, ")
  _sql.Append("Products.ReorderLevel, Ranges.MinValue, Ranges.MaxValue ")
  _sql.Append("FROM Products INNER JOIN ")
  _sql.Append("Categories ON Products.CategoryID = Categories.CategoryID ")
  _sql.Append("INNER JOIN Ranges ON Categories.CategoryID = Ranges.CategoryID ")

  Dim _con As New SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=;")
  Dim _cmd As New SqlCommand(_sql.ToString(), _con)

  Try

    _con.Open()
    DataGrid1.DataSource = _cmd.ExecuteReader()
    DataGrid1.DataBind()

  Catch _ex As Exception

    HttpContext.Current.Trace.Warn(_ex.Message)
    HttpContext.Current.Trace.Warn(_ex.StackTrace)
    HttpContext.Current.Trace.Warn(_ex.Source)

  Finally

    If (Not _con Is Nothing) AndAlso (_con.State = ConnectionState.Open) Then
      _con.Close()
    End If

  End Try

End Sub

Setting the RangeValidator Properties From Database Data

For the ReorderLevel field I used standard databinding expressions to set the MinimumValue and MaximumValue properties of the RangeValidator, as well as dynamically construct the error message that is displayed to the user. Using standard databinding expressions I am able to set the properties of the Range validator. The results are shown in Figure 2.

<asp:RangeValidator Runat="server" ControlToValidate="txtReorderLevel"
 MinimumValue='<%# DataBinder.Eval(Container.DataItem, "MinValue") %>'
 MaximumValue='<%# DataBinder.Eval(Container.DataItem, "MaxValue") %>'
 Type="Integer" Display="Dynamic">
  Reorder Level must be between <%# DataBinder.Eval(Container.DataItem, "MinValue") %>
  and <%# DataBinder.Eval(Container.DataItem, "MaxValue") %>.
</asp:RangeValidator>

Figure 2 - The DataGrid in Use

Summary

Any Web Server control can have its properties set either declaratively or programmatically. The validator controls are no exception. In this tutorial I showed you how to include validator controls in an EditItemTemplate of a DataGrid and set the validator properties either declaratively or programmatically.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值