Reputation: 813
I have database with table tbl_employee. In the table I store usernames. I use the following code to save all the usernames into a List:
string name = txtUsername.Text;
List<string> lst = new List<string>();
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=db;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT username FROM tbl_employee";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
lst.Add(dr.GetString(0));
}
Now, my question is how can I search through my list (lst) to see if the users input from textbox (name) exists in the list?
I have tried this:
if (lst.FindString(name))
//Says it has some invalid arguments
And this:
if (lst.Exists(element => element == name))
//It says name exists even though it doesn't
Upvotes: 0
Views: 168
Reputation: 813
Thanks quys! I changed it to count, as you suggested. Here is my final code:
string name = txtUsername.Text;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=db;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT COUNT(*) FROM tbl_employee WHERE username = @val1";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("@val1", name);
var result = command.ExecuteScalar();
int i = Convert.ToInt32(result);
if (i != 0)
{
FormsAuthentication.RedirectFromLoginPage(name, Persist.Checked);
}
else
{
lblMessage.Text = "Invalid username or password";
}
Upvotes: 1
Reputation: 149078
You could just use Contains
:
if (lst.Contains(name)) ...
But if this is all you're doing with the list, I'd recommend changing this code so it queries the tbl_empoyee
table directly from the database. I'm not familiar with the NpgsqlCommand
but it should look a bit like this:
bool result = false;
string sql = "SELECT username FROM tbl_employee WHERE username = :name";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("name", name);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
result = true; // record found
}
Or like this (following Tim Schmelter's suggestion):
string sql = "SELECT COUNT(*) FROM tbl_employee WHERE username = :name";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("name", name);
int found = (int)command.ExecuteScalar(); // 1 = found; 0 = not found
Upvotes: 3