Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 135,931 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,647 people online right now. Registration is fast and FREE... Join Now!




Yet another C# problem that involves a database

 
Reply to this topicStart new topic

Yet another C# problem that involves a database

sleepwalker
20 May, 2008 - 10:32 AM
Post #1

New D.I.C Head
*

Joined: 20 May, 2008
Posts: 4


My Contributions
First of all, I wanna say that this is my first post on dreamincode. Although I've been surfing the forum for some time now, it didn't cross my mind to actually create an account.. until now..
I've got this problem.. I've made a C# form that connects remotely to a database. The database stores some usernames and passwords which are used to login into my program. So far, so good, the connection works, both from my pc and from others. But I have a problem: I have to textboxes where I write the user's name and the password. Now, I'm stuck at the point where I want to compare the data from the textboxes to the fields of the database... I tried with a foreach, but it only works if i enter the first username and its password from the database. If I try to login using any other username and pass, it won't work.
Could someone please give me a hand?... Here's my code:
CODE
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.Odbc;

namespace Alocare_resurse
{
    public partial class Form1 : Form
    {
        
        string _host = "host";
        string _port = "port";
        string _database = "DataConnect";
        string _uid = "root";
        string _pwd = "****";//don't think you'd be interested in my pass:-D
        OdbcConnection _conn;
        OdbcCommand _com;
        OdbcDataReader _read;
        string _strcon;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dataSet1.users' table. You can move, or remove it, as needed.
            this.usersTableAdapter.Fill(this.dataSet1.users);
            _strcon = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=" + _host + ";PORT=" + _port + ";DATABASE=" + _database + ";UID=" + _uid + ";PWD=" + _pwd + ";OPTION=3";
            _conn = new OdbcConnection(_strcon);
            try
            {
                if (_conn.State == ConnectionState.Closed)
                {
                    _conn.Open();
                }
                MessageBox.Show("Conexiunea s-a realizat!");
            }
            catch (OdbcException ex)
            {
                MessageBox.Show("Nu s-a realizat conectarea la BD.\r\nAsigurati-va ca sunteti conectat la internet.\r\n\r\nMai multe detalii:\r\n" + ex.Message, "Database connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void clearbtn_Click(object sender, EventArgs e)
        {
            namebox.Text = string.Empty;
            passbox.Text = string.Empty;
        }

        private void exitbtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void loginbtn_Click(object sender, EventArgs e)
        {
            OdbcDataAdapter _dadapter = new OdbcDataAdapter("SELECT * FROM users", _conn);
            DataSet _dset = new DataSet();
            _dadapter.Fill(_dset, "users");
            foreach (DataRow _drow in _dset.Tables[0].Rows)
            {
                if ((_dset.Tables[0].Rows.ToString()== namebox.Text) && (_dset.Tables[0].Rows.ToString() == passbox.Text))
                {
                    loginbtn.Text = "Logout";
                    label3.Text = "Active";
                }
                else
                {
                    MessageBox.Show("Wrong username and/or password. Please reenter the data.", "Warning");
                }
            }

        }
    }
}


Thank you very much in advance.
User is offlineProfile CardPM
+Quote Post

zakary
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 10:44 AM
Post #2

D.I.C Regular
Group Icon

Joined: 15 Feb, 2005
Posts: 404



Thanked: 6 times
Dream Kudos: 175
My Contributions
instead of foreach try this
csharp

for(int i=0; i< _dset.Tables["NameOfDataTableToFine"].Rows;i++)
{
if ((_dset.Tables["NameOfDataTableToFine"].Rows[i].ToString() == namebox.Text)
&& (_dset.Tables["NameOfDataTableToFine"].Rows[i].ToString() == passbox.Text))
{
loginbtn.Text = "Logout";
label3.Text = "Active";
}
else
{
MessageBox.Show("Wrong username and/or password. Please reenter the data.", "Warning");
}
}


This post has been edited by zakary: 20 May, 2008 - 10:45 AM
User is online!Profile CardPM
+Quote Post

sleepwalker
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 10:52 AM
Post #3

New D.I.C Head
*

Joined: 20 May, 2008
Posts: 4


My Contributions
QUOTE(zakary @ 20 May, 2008 - 11:44 AM) *

instead of foreach try this
csharp

for(int i=0; i< _dset.Tables["NameOfDataTableToFine"].Rows;i++)
{
if ((_dset.Tables["NameOfDataTableToFine"].Rows.ToString() == namebox.Text)
&& (_dset.Tables["NameOfDataTableToFine"].Rows[i].ToString() == passbox.Text))
{
loginbtn.Text = "Logout";
label3.Text = "Active";
}
else
{
MessageBox.Show("Wrong username and/or password. Please reenter the data.", "Warning");
}
}



Thank you for the reply. I've already tried that.. and i get this error [i]Operator "<" cannot be applied to operands of type int and System.Data.Dataset
...

This post has been edited by sleepwalker: 20 May, 2008 - 10:53 AM
User is offlineProfile CardPM
+Quote Post

zakary
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 11:01 AM
Post #4

D.I.C Regular
Group Icon

Joined: 15 Feb, 2005
Posts: 404



Thanked: 6 times
Dream Kudos: 175
My Contributions
this if ((_dset.Tables["NameOfDataTableToFine"].Rows<i>.ToString() is wrong should be if ((_dset.Tables["NameOfDataTableToFine"].Rows[i].ToString()
User is online!Profile CardPM
+Quote Post

sleepwalker
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 11:04 AM
Post #5

New D.I.C Head
*

Joined: 20 May, 2008
Posts: 4


My Contributions
No.. it's not there, but here:
CODE
for (int i = 0; i < _dset.Tables[0].Rows; i++)


tried even with .ToString() laugh.gif, although i knew it wouldn't work...
User is offlineProfile CardPM
+Quote Post

zakary
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 11:17 AM
Post #6

D.I.C Regular
Group Icon

Joined: 15 Feb, 2005
Posts: 404



Thanked: 6 times
Dream Kudos: 175
My Contributions
use a string value of the name of the datatable u want to fine the user names and passwords in

// "NameOfDataTableToFine" is the name of the datatable.
for(int i=0; i< _dset.Tables["NameOfDataTableToFine"].Rows;i++)

but
for (int i = 0; i < _dset.Tables[0].Rows; i++)
should not be causing you the error [i]Operator "<" cannot be applied to operands of type int and System.Data.Dataset...

this
Rows<i>.ToString()
will
User is online!Profile CardPM
+Quote Post

baavgai
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 11:18 AM
Post #7

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,015



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
First, do NOT open your connection when you open the form. Second, the DataAdapter does need it open, anyway; it opens and closes it itself. Also, what's with all the underscores? They're usually used to show object variables and you've got them everywhere. Do they mean something?

This is kind of meaningless:
CODE

if ((_dset.Tables[0].Rows.ToString()== namebox.Text) && (_dset.Tables[0].Rows.ToString() == passbox.Text))


It should look more like:
CODE

// assuming first field is username, second is password
if (_drow[0] == namebox.Text) && _drow[1] == passbox.Text )


Here's some cleaned up code to get you on your way:
csharp

namespace Alocare_resurse {
public partial class Form1 : Form {

public Form1() { InitializeComponent(); }

// define where you get a connection once. You might have this code elsewhere
private OdbcConnection GetNewConnection() {
return new OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}"
+";SERVER=" + "host"
+ ";PORT=" + "port"
+ ";DATABASE=" + "DataConnect"
+ ";UID=" + "root"
+ ";PWD=" + "****"
+ ";OPTION=3";
}

private void Form1_Load(object sender, EventArgs e) {
// I'm confused, do you alread have an adapter?
// TODO: This line of code loads data into the 'dataSet1.users' table. You can move, or remove it, as needed.
this.usersTableAdapter.Fill(this.dataSet1.users);
CheckConnection();
}

private void CheckConnection() {
OdbcConnection conn = GetNewConnection();
try {
conn.Open();
MessageBox.Show("Conexiunea s-a realizat!");
} catch (OdbcException ex) {
MessageBox.Show("Nu s-a realizat conectarea la BD.\r\nAsigurati-va ca sunteti conectat la internet.\r\n\r\nMai multe detalii:\r\n" + ex.Message, "Database connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} finally {
conn.Close();
}
}



// Use a data table, we're only getting that much
private DataTable GetUsers() {
// we'll assume you have these two columns
OdbcDataAdapter da = new OdbcDataAdapter("SELECT username, password FROM users", GetNewConnection());
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

private void loginbtn_Click(object sender, EventArgs e) {
bool found = false;
string enteredUserName = namebox.Text.Trim();
string enteredPassword = namebox.Text.Trim();

// no point in bothering if they're blank
if (enteredUserName!="" && enteredPassword!="") {
DataTable dtUsers = GetUsers();
// loop until you find them ( or not )
foreach (DataRow row in dtUsers.Rows) {
if (row[0]==enteredUserName) {
// assume we'll only have one entry for user name
found = (row[1]==enteredPassword);
break;
}
}
}
if (found) {
loginbtn.Text = "Logout";
label3.Text = "Active";
} else{
MessageBox.Show("Wrong username and/or password. Please reenter the data.", "Warning");
}
}
}
}


Hope this helps.

User is offlineProfile CardPM
+Quote Post

sleepwalker
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 11:30 AM
Post #8

New D.I.C Head
*

Joined: 20 May, 2008
Posts: 4


My Contributions
Thank you, baavgai, for cleaning my code... I'll try it and hopefully it will work. Again, may thanks, both to you and zakary.
User is offlineProfile CardPM
+Quote Post

eclipsed4utoo
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 12:14 PM
Post #9

D.I.C Regular
Group Icon

Joined: 21 Mar, 2008
Posts: 349



Thanked: 19 times
Dream Kudos: 25
My Contributions
in case nobody noticed....you had an error in your FOR loop.

your code:

C#

for(int i=0; i< _dset.Tables["NameOfDataTableToFine"].Rows;i++)
{

}


correct code;

C#

for(int i=0; i< _dset.Tables["NameOfDataTableToFine"].Rows.Count;i++)
{

}

User is offlineProfile CardPM
+Quote Post

thor78
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 04:09 PM
Post #10

D.I.C Head
Group Icon

Joined: 6 May, 2008
Posts: 106


Dream Kudos: 50
My Contributions
You could filter your result set right away by including a WHERE "user" AND "pass" in your select statement and simply check if the result set has any rows that match your query. smile.gif
User is offlineProfile CardPM
+Quote Post

baavgai
RE: Yet Another C# Problem That Involves A Database
20 May, 2008 - 06:11 PM
Post #11

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,015



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
QUOTE(thor78 @ 20 May, 2008 - 08:09 PM) *

You could filter your result set right away by including a WHERE "user" AND "pass" in your select statement and simply check if the result set has any rows that match your query. smile.gif


Shh, that's phase II. wink2.gif But you're right, all the looping through an entire dataset is wasteful. I would write a SQL Command with a bind variable for user that returns the single value of password. If nothing is returned, it's an invalid user. If the password doesn't match, chances are they'll keep the user and enter a different password, saving a database call.

I considered writing a blog about this one, I've seen the approach of pull it all down and then search through it a lot lately. Databases are made for searching; a programmatic search is rarely needed.

That said, there are occasions when properly iterating through a DataTable is required and thus good to know. Of course, the DataTable also has a Search method... phase 1.5.

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/1/08 08:23AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month