2014-10-13 3 views
0

При получении значений из базы данных я проверяю, содержит ли значение текстового поля в массиве. Массив содержит извлеченные значения из базы данных. Если он содержит значение, он должен показывать метку. Это работает до тех пор, пока я не добавлю else в оператор if, после чего ярлык откажется показывать.Ярлык не отображается, если найден дубликат asp.net

Главная:

<asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    <ContentTemplate> 
     <asp:MultiView ID="ManageCourseMultiView" ActiveViewIndex="1" runat="server"> 
      <asp:View ID="OptionsView" runat="server"> 
       <asp:LinkButton ID="CourseLinkButton" CommandName="SwitchViewByID" CommandArgument="ManageCourseView" runat="server">Please click here to manage your course.</asp:LinkButton> 
       &nbsp; 
       <asp:LinkButton ID="CourseContentLinkButton" CommandName="SwitchViewByID" CommandArgument="ManageCourseContentView" runat="server">Please click here to manage your course content.</asp:LinkButton>&nbsp;&nbsp;&nbsp;&nbsp; 
       <asp:HyperLink ID="CreateCourseLink" NavigateUrl="~/Instructors/CreateCourse2.aspx" runat="server">Please click here to create a course.</asp:HyperLink> 
       <br /> 
       <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT * FROM [Course] WHERE ([CourseId] = @CourseId)"> 
        <SelectParameters> 
         <asp:ControlParameter ControlID="GridView1" Name="CourseId" PropertyName="SelectedValue" Type="Int32" /> 
        </SelectParameters> 
       </asp:SqlDataSource> 
      </asp:View> 
      <asp:View ID="ManageCourseView" runat="server"> 
       <asp:Label ID="UserIdLabel" Visible="true" runat="server" Text="Label"></asp:Label> 
       <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" DataKeyNames="CourseId" DataSourceID="GridViewSource" Width="1072px"> 
        <Columns> 
         <asp:CommandField ShowSelectButton="True" /> 
         <asp:BoundField DataField="CourseId" HeaderText="CourseId" InsertVisible="False" ReadOnly="True" SortExpression="CourseId" /> 
         <asp:BoundField DataField="CourseName" HeaderText="CourseName" SortExpression="CourseName" /> 
         <asp:BoundField DataField="ForRole" HeaderText="ForRole" SortExpression="ForRole" /> 
         <asp:CheckBoxField DataField="Certification" HeaderText="Certification" SortExpression="Certification" /> 
         <asp:BoundField DataField="UserId" Visible="false" HeaderText="UserId" SortExpression="UserId" /> 
        </Columns> 
       </asp:GridView> 
       <asp:SqlDataSource ID="GridViewSource" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT Course.* FROM Course WHERE (UserId = @UserId)"> 
        <SelectParameters> 
         <asp:ControlParameter ControlID="UserIdLabel" Name="UserId" PropertyName="Text" /> 
        </SelectParameters> 
       </asp:SqlDataSource> 
       <br /> 
       <table> 
        <tr> 
         <td> 
          <asp:Label ID="CourseEditName" runat="server" Text="Course Name:"></asp:Label> 
         </td> 
         <td> 
          <asp:TextBox ID="CourseEditNameTextBox" runat="server"></asp:TextBox>&nbsp; 
          <asp:Label ID="nameerror" runat="server" ForeColor="Red" Visible="false" Text="This Coursename already exists, please enter another one."></asp:Label> 
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ForeColor="Red" ControlToValidate="CourseEditNameTextBox" ErrorMessage="Course Name cannot be empty."></asp:RequiredFieldValidator> 
         </td> 
        </tr> 
        <tr> 
         <td> 
          <asp:Label ID="CourseEditForRoles" runat="server" Text="For Role: "></asp:Label> 
         </td> 
         <td> 
          <asp:DropDownList ID="CourseEditForRole" runat="server"> 
           <asp:ListItem Text="Parent" Value="Parent"></asp:ListItem> 
           <asp:ListItem Text="Staff" Value="Staff"></asp:ListItem> 
           <asp:ListItem Text="Health Care PRofessional" Value="HealthPro"></asp:ListItem> 
          </asp:DropDownList> 
          <asp:SqlDataSource ID="ForRoleUpdate" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT RoleName FROM Roles WHERE (RoleName &lt;&gt; 'BackOffice') AND (RoleName &lt;&gt; 'Instructor')"></asp:SqlDataSource> 
         </td> 
        </tr> 
        <tr> 
         <td> 
          <asp:Label ID="CourseEditCertification" runat="server" Text="Certification: "></asp:Label> 
         </td> 
         <td> 
          <asp:CheckBox ID="CourseEditCertificationCheckBox" runat="server" /> 
         </td> 
        </tr> 
        <tr> 
         <td> 
          <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label5" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label7" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label8" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label9" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label10" runat="server" Text="Label"></asp:Label> 
          <asp:Label ID="Label11" runat="server" Text="Label"></asp:Label> 
         </td> 
         <td> 
          <asp:Button ID="CourseEditUpdate" OnClick="CourseEditUpdate_Click" runat="server" Text="Finish Editing" /> 
          <asp:Button ID="CourseEditCancel" runat="server" CommandName="Cancel" CausesValidation="false" Text="Cancel" /> 
         </td> 
        </tr> 
       </table> 
       <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" DeleteCommand="DELETE FROM [Course] WHERE [CourseId] = @CourseId" InsertCommand="INSERT INTO [Course] ([CourseName], [ForRole], [Certification], [UserId]) VALUES (@CourseName, @ForRole, @Certification, @UserId)" SelectCommand="SELECT * FROM [Course]" UpdateCommand="UPDATE [Course] SET [CourseName] = @CourseName, [ForRole] = @ForRole, [Certification] = @Certification, [UserId] = @UserId WHERE [CourseId] = @CourseId"> 
        <DeleteParameters> 
         <asp:Parameter Name="CourseId" Type="Int32" /> 
        </DeleteParameters> 
        <InsertParameters> 
         <asp:Parameter Name="CourseName" Type="String" /> 
         <asp:Parameter Name="ForRole" Type="String" /> 
         <asp:Parameter Name="Certification" Type="Boolean" /> 
         <asp:Parameter Name="UserId" Type="Object" /> 
        </InsertParameters> 
        <UpdateParameters> 
         <asp:Parameter Name="CourseName" Type="String" /> 
         <asp:Parameter Name="ForRole" Type="String" /> 
         <asp:Parameter Name="Certification" Type="Boolean" /> 
         <asp:Parameter Name="UserId" Type="Object" /> 
         <asp:Parameter Name="CourseId" Type="Int32" /> 
        </UpdateParameters> 
       </asp:SqlDataSource> 
      </asp:View> 
      <asp:View ID="ManageCourseContentView" runat="server"> 
       <h2>Test</h2> 
      </asp:View> 
     </asp:MultiView> 
    </ContentTemplate> 
</asp:UpdatePanel> 

CodeBhind:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 

    Boolean checkboxvalue; 
    string cert; 
    using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) 
    { 
     connection.Open(); 
     using (var command = connection.CreateCommand()) 
     { 
      command.CommandText = "SELECT * FROM Course WHERE CourseId = '" + GridView1.SelectedValue.ToString() + "'"; 
      using (var reader = command.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        CourseEditForRole.SelectedValue = reader["ForRole"].ToString(); 
        CourseEditNameTextBox.Text = reader["CourseName"].ToString(); 
        checkboxvalue = Convert.ToBoolean(reader["Certification"]); 
        cert = reader["Certification"].ToString(); 
        if (cert == "False") 
        { 
         CourseEditCertificationCheckBox.Checked = false; 
        } 
        else 
        { 
         CourseEditCertificationCheckBox.Checked = true; 
        } 
       } 
      } 
     } 
     using (var command = connection.CreateCommand()) 
     { 
      command.CommandText = "SELECT CourseName FROM Course WHERE (CourseId = '" + GridView1.SelectedValue.ToString() + "')"; 
      using (var reader = command.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        coursenamevalue = reader["CourseName"].ToString(); 
       } 
      } 
     } 
     using (var command2 = connection.CreateCommand()) 
     { 
      command2.CommandText = "SELECT CourseName FROM [Course] WHERE (CourseName <> '" + coursenamevalue + "')"; 
      using (var reader = command2.ExecuteReader()) 
      { 
       int i = 0; 
       while (reader.Read()) 
       { 
        coursename[i] = reader["CourseName"].ToString(); 
        i++; 
       } 
       counter = i; 
      } 
     } 
    } 
} 
protected void CourseEditUpdate_Click(object sender, EventArgs e) 
{ 
    Boolean checkboxvalue; 
    string cert; 
    using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) 
    { 
     connection.Open(); 
     using (var command2 = connection.CreateCommand()) 
     { 
      command2.CommandText = "SELECT CourseName FROM [Course] WHERE (CourseName <> '" + coursenamevalue + "')"; 
      using (var reader = command2.ExecuteReader()) 
      { 
       int i = 0; 
       while (reader.Read()) 
       { 
        coursename[i] = reader["CourseName"].ToString(); 
        if (CourseEditNameTextBox.Text.Equals(reader["CourseName"].ToString(), StringComparison.Ordinal)) 
        { 
         //cameerror.Visible = true; 
        } 
        i++; 
       } 
       counter = i; 
      } 
     } 
    } 
    int k = 0; 

    while(!String.IsNullOrEmpty(coursename[k])) 
    { 
     if (coursename[k].Contains(CourseEditNameTextBox.Text)) 
     { 
      nameerror.Visible = true; 
     } 
     else 
     { 
      nameerror.Visible = false; 
     } 
     k++; 
    } 
} 
+0

Каков тип courseame в курсе EditUpdate_Click? –

+0

coursename имеет тип string array – Jomino

ответ

0

Проблема в том, вы по-прежнему в то время цикла, если его существование необходимо разорвать петлю, потому что это последний элемент массива иначе, чем содержимое текстового поля, эта метка исчезнет, ​​вы должны сделать это:

int k = 0; 

while(!String.IsNullOrEmpty(coursename[k])) 
{ 
    if (coursename[k].Contains(CourseEditNameTextBox.Text)) 
    { 
     nameerror.Visible = true; 
     Break; 
    } 
    else 
    { 
     nameerror.Visible = false; 
    } 
    k++; 
} 
+0

О, спасибо, кучи для этого, не могу поверить, что он не работал, потому что я не выходил из цикла. – Jomino

+0

Добро пожаловать :), это случается много;) –

Смежные вопросы