Udit Khanna
Udit Khanna

Reputation: 45

control not working properly

I am trying to use the keydown feature .My code is up and running but am getting this strange error.I am running a query where if in the database column value is MIND then the radiobutton mind should be checked else MSSL.but the control always goes into else part no matter ,the value in the database is MIND or MSSL. Following is my code

    private void txtlogin_userid_KeyDown(object sender, KeyEventArgs e)
     {
       if (e.KeyCode == Keys.Enter)
         {
           if (sender is TextBox)
           {
        TextBox txb = (TextBox)sender;
        dc.SelectCommand = new SqlCommand("select * from UserMaster where UserID='" + txb.Text + "'", sc);
        dc.Fill(ds);
        dg.DataSource = ds.Tables[0];
        txtlogin_name.Text = ds.Tables[0].Rows[0][1].ToString();
        txtlogin_mailid.Text = ds.Tables[0].Rows[0][2].ToString();
        MessageBox.Show(ds.Tables[0].Rows[0][3].ToString());
        string a = "MIND";

        if (ds.Tables[0].Rows[0][3].ToString() == a)
        {
            radiomind.Checked = true;
        }
        else
        {
            radioMSSL.Checked = true;
        }
    }
}}

when i enter the any number that has MIND as its value in the database,the message box shows MIND but still the control goes into else part and the MSSL radio button activates.what to do?

Upvotes: 0

Views: 98

Answers (3)

the_lotus
the_lotus

Reputation: 12748

Put a break point on each of the radio[...].Checked, is it really going into the else? Maybe the radio button variable name are wrong. Maybe the radio button are being reset somewhere else.

    if (ds.Tables[0].Rows[0][3].ToString() == a)
    {
        MessageBox.Show("mind");
        radiomind.Checked = true;
    }
    else
    {
        MessageBox.Show("mssl");
        radioMSSL.Checked = true;
    }

Check the exact value of each strings you are comparing. Do they have extra space, characters? Sometime a string can have an extra white space.

MessageBox.Show("[" + ds.Tables[0].Rows[0][3].ToString() + "]"); 
MessageBox.Show(ds.Tables[0].Rows[0][3].ToString().Length); 
MessageBox.Show("[" + a + "]"); 
MessageBox.Show(a.Length);

Side note

Like Quibblesome said, you should use SqlParameters cause you are vulnerable to sql-injections.

If you are doing select *, you might have errors in the futur if the order of your columsn changes.

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112782

Try

if (e.KeyCode == Keys.Return)

instead of Keys.Enter.


If you write

private void txtlogin_userid_KeyDown(object sender, KeyEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.KeyCode);
}

You will see the actual code in the Output Window (open with menu: Debug > Windows > Output).

Upvotes: 0

fiscblog
fiscblog

Reputation: 694

Try

        Convert.ToString(ds.Tables[0].Rows[0][3]) == a 

Instead.

Upvotes: 0

Related Questions