如何使用asp.net检查网格视图的第一行和第一列

时间:2012-10-17 07:04:00

标签: asp.net

我有一个有两列的gridview。我想检查第一行,第一列应该是强制性的。如果第一列为空,则不应允许保存,并且应将消息显示为

  

一行应该是强制性的。

如何检查?

我的保存按钮点击编码如下

Dim row As GridViewRow 
For Each row In GridView1.Rows 
If row.RowType = DataControlRowType.DataRow Then 
    Dim t1 As String = CType(row.FindControl("TextBox2"), TextBox).Text 
    Dim dd As String = CType(row.FindControl("DropDownList3"), DropDownList).SelectedItem.Text 
    If Trim(t1) = "" Or (Trim(dd)= "" then 
        label6.Text = "HospNo,Date,SurgeryCode/Method are Mandatory" 
    End If 

但是这会检查所有网格列,我只想检查第一行和第一列。

2 个答案:

答案 0 :(得分:0)

For Each row In GridView1.Rows 
 If row.RowType = DataControlRowType.DataRow Then 
 Dim t1 As String = CType(row.FindControl("TextBox2"), TextBox).Text 
 Dim dd As String = CType(row.FindControl("DropDownList3"),DropDownList).SelectedItem.Text 
If Trim(t1) = "" Or (Trim(dd)= "" then 
    label6.Text = "HospNo,Date,SurgeryCode/Method are Mandatory" 
End If
 Exit For
 End For  

答案 1 :(得分:0)

您可以使用GridView1.Rows(0)获取第一行:

Dim firstRow = GridView1.Rows(0)
Dim TextBox2 = DirectCast(firstRow.FindControl("TextBox2"), TextBox)
Dim DropDownList3 = DirectCast(firstRow.FindControl("DropDownList3"), DropDownList)
If TextBox2.Text.Trim.Length = 0 OrElse DropDownList3.SelectedIndex = -1 Then
    label6.Text = "HospNo,Date,SurgeryCode/Method are Mandatory"
End If

但这不是你应该在ASP.NET中使用的方法。而是使用RequiredFieldValidator,它可以在客户端进行验证。

例如:

<asp:GridView ID="GridView1" OnSelectedIndexChanged="Grid1_SelectedIndexChanged"  AutoGenerateSelectButton="true" AutoGenerateColumns="false" runat="server" Width="300">
        <RowStyle  CssClass="GridViewRowStyle" />
        <AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
        <HeaderStyle CssClass="GridViewHeaderStyle" />
        <SelectedRowStyle BackColor="Aqua" />
        <Columns>
            <asp:TemplateField HeaderText="Column 1" HeaderStyle-HorizontalAlign="Left">
               <ItemTemplate>
                    <asp:TextBox runat="server" ID="TxtColumn1" Text='<%# Bind("Column1") %>'></asp:TextBox>
                    <asp:RequiredFieldValidator id="RequiredFieldValidator1"
                        EnableClientScript="true"
                        ControlToValidate="TxtColumn1"
                        Display="Static"
                        ErrorMessage="HospNo,Date,SurgeryCode/Method are Mandatory" 
                        runat="server"/> 
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
   </asp:GridView>