检查与数据库ASP.NET C#的重复 [英] Check duplication with the database ASP.NET C#

查看:72
本文介绍了检查与数据库ASP.NET C#的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我想显示错误信息而不是错误页面,我的问题是我应该把我的代码放在哪里..任何帮助??









I have a details view and button and I want when I click on the button to check if the username is already in the database or not, I tried the below code but it goes to the else statement even if the username exists.

I want to show an error message instead of the error page, my question is where should i put my code .. Any Help??




<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>





What I have tried:





What I have tried:

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());


     }
     }
     }

推荐答案

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>
& lt;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 ButtonT ype=\"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>
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>





What I have tried:





What I have tried:

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());


     }
     }
     }


I would say the code you shared is rather kid’ish.. Anyways, here is the issue and suggestion to make it better

Issue:
I would say the code you shared is rather kid'ish.. Anyways, here is the issue and suggestion to make it better
Issue:
select Username from [Login]

Query will return all the usernames from database. So, you are iterating the whole result set. Assuming that the username will occur just once in you table, the if condition will return true just one, and for rest of the time it will fall in else and hence the issue. To fix this, exit the loop as soon as you enter the if condition. It will terminate the loop.



I could not see the purpose of this loop unless you make us understand.



Suggestion:

Filter the result set in your SQL query by writing

Query will return all the usernames from database. So, you are iterating the whole result set. Assuming that the username will occur just once in you table, the if condition will return true just one, and for rest of the time it will fall in else and hence the issue. To fix this, exit the loop as soon as you enter the if condition. It will terminate the loop.

I could not see the purpose of this loop unless you make us understand.

Suggestion:
Filter the result set in your SQL query by writing

select Username from [Login] WHERE Username = '<username from textbox>'

This will allow you to check the database for username without iterating the entire result set. Think of a scenario where you have 10000 users and they all are accessing your page. It will make you loop run 10000*10000 times.

This will allow you to check the database for username without iterating the entire result set. Think of a scenario where you have 10000 users and they all are accessing your page. It will make you loop run 10000*10000 times.


这篇关于检查与数据库ASP.NET C#的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆