使用SQL成员资格提供程序获取ASP.NET成员资格。我使用first.last作为用户名,这是通过在表单上填写的用户详细信息以编程方式创建的。
当用户提交表单时,我希望能够检查用户名是否存在,如果是,则将其更改为username1,检查username1是否存在,如果存在则将其设置为username2等,直到用户名为唯一用户名为止。
我不知道如何做存储过程,所以我正在尝试使用SQLDataReader来检查用户名是否存在。
问题是我的循环。逻辑基本上是设置一个布尔值并保持循环并向计数器添加1,直到它找不到重复。我已经多次介入,即使它将布尔值设置为false,它也会保持循环。
想法好吗?
代码背后:
protected void Membership_add()
{
SqlConnection con = new SqlConnection(connectionString);
string NewUserNameString = FirstName.Text + "." + LastName.Text;
//Check for duplicate aspnet membership name and add a counter to it if exists
// Check for valid open database connection before query database
bool match = true;
SqlDataReader _SqlDataReader = null;
string TestNameString = NewUserNameString;
string selectDupeString = "SELECT UserId FROM aspnet_Users WHERE UserName = '" + TestNameString + "'";
SqlCommand SQLdatareaderCmd = new SqlCommand(selectDupeString, con);
int UserNameCounter = 0;
con.Open();
while (match = true)
{
//Open the connection
try
{
//Read the table
_SqlDataReader = SQLdatareaderCmd.ExecuteReader();
}
catch (Exception ex)
{
lblDatareaderEx.Text = "An Exception occurred. " + ex.Message + " " + ex.GetType().ToString();
}
if (_SqlDataReader.HasRows)
{
//match = true;
//increase counter by 1 for each record found and change First.Name to First.Namex
TestNameString = NewUserNameString;
UserNameCounter = UserNameCounter + 1;
TestNameString = TestNameString + UserNameCounter.ToString();
_SqlDataReader.Close();
_SqlDataReader.Dispose();
selectDupeString = "SELECT UserId FROM aspnet_Users WHERE UserName = '" + TestNameString + "'";
SQLdatareaderCmd = new SqlCommand(selectDupeString, con);
}
else
{
// close sql reader
_SqlDataReader.Close();
_SqlDataReader.Dispose();
//get out of loop
match = false;
}
}
con.Close();
con.Dispose();
}
答案 0 :(得分:1)
这一行:
while (match = true)
做作业 如果您希望代码工作,则必须进行比较:
while (match == true)
或者,既然你的变量已经是bool,你可以直接使用变量:
while(match)
答案 1 :(得分:0)
目前您正在设置match
而不是比较它的价值。
尝试将while (match = true)
设为while (match == true)
答案 2 :(得分:0)
如果将代码分解为更小的块,则代码变得更简单,更易于阅读。
private string MembershipAddUser(string firstName, string lastName)
{
string username = firstName + "." + lastName;
int i = 0;
while (UserExists(username))
{
i++;
username = firstName + "." + lastName + i.ToString();
}
return username;
}
private bool UserExists(string username)
{
string sql = "SELECT COUNT(*) FROM dbo.aspnet_Users WHERE UserName = @UserName";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@UserName", username);
using (connection)
{
connection.Open();
int count = (int) command.ExecuteScalar();
return (count != 0);
}
}