使用数据库asp.net c#检查重复

时间:2017-04-27 11:15:32

标签: c# asp.net sql-server detailsview

我有一个详细信息视图和一个按钮,当我点击按钮时,我想检查用户名是否已经在数据库中。我尝试了下面的代码,但它转到了else语句,即使用户名存在。

任何帮助?

protected void Button2_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    string query = "select Username from [Login]";

    SqlCommand cmd = new SqlCommand(query);

    SqlDataAdapter sqlda = new SqlDataAdapter(cmd.CommandText, con);
    DataTable dt = new DataTable();
    sqlda.Fill(dt);

    int RowCount = dt.Rows.Count;

    for (int i = 0; i < RowCount; i++)
    {
        Label13.Text = ((TextBox)DetailsView1.FindControl("TextBox1")).Text;
        Label14.Text = dt.Rows[i]["Username"].ToString();

        if (Label13.Text == Label14.Text)
        {
            string message = "Username is Already Exists";

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<script type = 'text/javascript'>");
            sb.Append("window.onload=function(){");
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("')};");
            sb.Append("</script>");

            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
        }
        else
        {
            string message = "Successfully saved";

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<script type = 'text/javascript'>");
            sb.Append("window.onload=function(){");
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("')};");
            sb.Append("</script>");

            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
        }
    } 
}

详细信息视图标记:

<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
        CellPadding="4" DataKeyNames="Username" DataSourceID="SqlDataSource3" 
           ForeColor="#333333" GridLines="None" Height="50px" Width="283px" 
            style="margin-top: 0px; text-align: left;" 
           onitemupdated="DetailsView1_ItemUpdated" onitemdeleted="DetailsView1_ItemDeleted" 
           oniteminserted="DetailsView1_ItemInserted" DefaultMode="Insert" 
           oniteminserting="DetailsView1_ItemInserting">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
        <EditRowStyle BackColor="#999999" />
        <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
        <Fields>
            <asp:TemplateField HeaderText="Username" SortExpression="Username">
                <EditItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Username") %>' 
                        ValidationGroup="1"></asp:TextBox>
                    <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" 
                        ErrorMessage="*" ControlToValidate="TextBox1" ForeColor="Red" 
                        ValidationGroup="1"></asp:RequiredFieldValidator>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Password" SortExpression="Password">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>' ValidationGroup="1"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                        ControlToValidate="TextBox2" ErrorMessage="*" ForeColor="Red" 
                        ValidationGroup="1"></asp:RequiredFieldValidator>
                </InsertItemTemplate>
                <ItemTemplate>

                </ItemTemplate>
                <ControlStyle />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="UserType" SortExpression="UserType">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UserType") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:DropDownList ID="DropDownList4" runat="server" 
                        ConnectionString ="<%$ConnectionStrings: ConnectionString %>" 
                        SelectedValue='<%# Bind("UserType") %>' ValidationGroup="1">
                    <asp:ListItem>--Select--</asp:ListItem>
                    <asp:ListItem>employee</asp:ListItem>
                    <asp:ListItem>doctor</asp:ListItem>
                    <asp:ListItem>student</asp:ListItem>
                    </asp:DropDownList> 
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                        ControlToValidate="DropDownList4" ErrorMessage="*" ForeColor="Red" 
                        InitialValue="--Select--" ValidationGroup="1"></asp:RequiredFieldValidator>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("UserType") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ButtonType="Button" ShowInsertButton="True" ValidationGroup="1" />
        </Fields>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    </asp:DetailsView>

2 个答案:

答案 0 :(得分:1)

为什么不将用户名作为参数传递给Db。

  string query = "select Username from [Login] where Username=@username";
     var nameParam = new SqlParameter("username");
     nameParam.Value = Label13.Text;
     cmd.Parameters.Add(nameParam);

如果db。中存在用户名,它将仅获取记录。

然后使用rowCount检查它。

if(RowCount> 0){
    //Username exist
}else {
    //Do other work
}

答案 1 :(得分:0)

请你这样试试。

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = "select Username from [Login] WHERE Username='"+((TextBox)DetailsView1.FindControl("TextBox1")).Text+"'";

SqlCommand cmd = new SqlCommand(query);
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows())
{
// The username exist
}