Esther EatFries
Esther EatFries

Reputation: 47

c# if else looping

i need some help in the if else part. For now, my code shows "if row=0, user not found". But i would like it to loop whereby if nothing is detected, continues looping until the event changes. How do i do this looping here?

string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
string strSqlStatement = string.Empty;
strSqlStatement = "SELECT * FROM jiahe WHERE [Tag ID] = '" + txt + "'";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
DataSet ds = new DataSet();
objAdapter.Fill(ds);

DataTable dt = ds.Tables[0];
dataGridView1.DataSource = dt.DefaultView;

if (dt.Rows.Count == 0)
{
    MessageBox.Show("Not Found. Please register new user.");
    Form2 frm2 = new Form2();
    frm2.Show();
}
else
{
    string strLine = string.Empty;
    string strUser = string.Empty;

    foreach (DataRow dr in dt.Rows)
    {
        string strTags = dr["Tag ID"].ToString();
        strUser = dr["User"].ToString();
        string strAge = dr["Age"].ToString();
        string strPhoneNumber = dr["Phone Number"].ToString();

Upvotes: 1

Views: 379

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500065

Just to expand my comment into an answer - it feels to me like this is going in the wrong direction. I would change the design to something like (somewhat pseudo-code):

void FindUserOrRegister()
{
    User user = GetUserFromDatabase();
    if (user != null)
    {
        new MainApplicationForm(user).Show();
    }
    else
    {
        new RegistrationForm().Show();
    }
}

Then possibly make the RegistrationForm logic call FindUserOrRegister as part of its registration flow - if the user chooses to just close the form, then the whole app should close (presumably)... but otherwise, when registration completes, you can close the form then call FindUserOrRegister again, which will then launch the main form.

Alternatively, the registration form could just launch the main application directly after registration has completed.

I'm sort of guessing as to what you're trying to do here, but I do think it's at least worth separating the database code from the UI flow - and trying to do this in a more event-driven way, given that it's the user who will be changing whether or not you should proceed. If you were waiting for someone else to add a record to the database, you would be better with some sort of timer repeatedly querying the database (in a background thread - threading is another area you'll need to learn about in order to avoid your UI hanging while you query the database, btw) but here I don't think you need that.

Upvotes: 5

Related Questions