开发者

gridview check duplicates not using sql

I have a code:

foreach (GridViewRow dr in gvCategories.Rows)<br/>
{  
   <br/>
   if (dr.Cells[0].Text == txtEnterCategory.Text.Trim())<br/>
   <br/>
    isError=true;
   <br/>
   <br/> 
}

Debugging: dr.Cells[0].Text is always "", even there are records. How to use a loop to check each row to find if a record exists in the gridview not using sql?

More code:

in .ascx:

<Columns>
    <asp:TemplateField HeaderText="Category Name" SortExpression="Category">
    <ItemTemplate>
        <asp:Label ID="txtCategoryEdit" runat="server" Text='<%# Bind("CategoryName") %>' OnTextChanged="TextBox_TextChanged"></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
<asp:TextBox ID="txtCategoryEdit" runat="server" Text='<%# Bind("CategoryName") %>' OnTextChanged="TextBox_TextChanged"></asp:TextBox>
    </EditItemTemplate>

</asp:TemplateField>
<asp:TemplateField HeaderText="In Footer?" SortExpression="ShowInFooter">
    <ItemTemplate>
        <asp:Label ID="lblShowInFooter" runat="server" 
            Text='<%# (bool)Eval("ShowInFooter") ? "Yes" : "No" %>'></asp:Label>
    </ItemTemplate>
  <EditItemTemplate>
    <asp:CheckBox ID="lblShowInFooter" runat="server"
      Checked='<%# (bool)Eval("ShowInFooter")%>'>
    </asp:CheckBox>

  </EditItemTemplate>

</asp:TemplateField>


 <asp:CommandField ShowCancelButton开发者_如何学C="true" ShowDeleteButton="true" ShowEditButton="true" CausesValidation="false" ItemStyle-CssClass="commandfield" />
</Columns>

in ascx.cs:

bool isError = false;

foreach (GridViewRow dr in gvCategories.Rows)
    {
        if (dr.Cells[0].Text == txtEnterCategory.Text.Trim())
        {
            lblErrorMessage.Text = "This category already exits. Please enter a new category!";
            lblErrorMessage.Visible = true;

            isError=true;

        }


    }


Since you've got a TemplateField containing a Label in the leftmost column, rather than a BoundField, you get the value out like this:

foreach (GridViewRow dr in gvCategories.Rows)
{
    Label l = (Label)dr.Cells[0].Controls[1];

    if (l.Text.Trim() == txtEnterCategory.Text.Trim())
    {
        lblErrorMessage.Text = "This category already exits. Please enter a new category!";
        lblErrorMessage.Visible = true;

        isError=true;
    }

Don't ask me why it's Controls[1], but it is. Every control in a TemplateField's ItemTemplate seems to create a pair of controls, so for example, if you had this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:TextBox ID="txtFoo" runat="server" />
        <asp:TextBox ID="txtBar" runat="server" />
    </ItemTemplate>
</asp:TemplateField>

txtFoo would be at Controls[1] and txtBar would be at Controls[3].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜