0

My C# program is connected to my SQL CE Database. I use a SQLCEDATAREADER to fill some of the textboxes in my program. I have a "Gender" column in my database and a radiobutton with Male and Female. If a certain entry in my database has "M" in the gender column, how can I make the Male radio button appear pressed?

I tried

if(dr["Gender"].ToString = "M")
{
    rbMale = true
}

That obviously didnt work.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Dave Howson
  • 156
  • 6
  • 14
  • 2
    What do you mean by _didn't work_? You get any exception or error message? `=` is an assingment operator, if you wanna compare your strings, you need to use `==` instead. Since `ToString` is a method, you need to use it as `ToString()`. And `rbMale = true` needs to `;` at the end of the line. – Soner Gönül Mar 02 '15 at 08:51
  • Right syntax should be `if(dr["Gender"].ToString() == "M") { rbMale = true; }` but we _still_ need more information about your problem. – Soner Gönül Mar 02 '15 at 08:55
  • Well it says "Cannot implicitly convert type 'bool' to 'System.Windows.Forms.RadioButton" – Dave Howson Mar 02 '15 at 08:58
  • Looks like `rbMale` is `RadioButton`, it is too normal to get this error. Look it's `Checked` property. You can get and set this property if your condition returns `true`. – Soner Gönül Mar 02 '15 at 09:03

3 Answers3

1
if(dr["Gender"].ToString() = "M")
    rbMale.Checked = true
else
    rbFemale.Checked = true
JoeBilly
  • 3,057
  • 29
  • 35
Vynhoû Tawa
  • 68
  • 1
  • 14
1

Perhaps collapse to one line -

rbMale.Checked = (Convert.ToString(dr["Gender"])=="M");
jammy
  • 31
  • 3
  • This answer is definitly better. : one line boolean affectation, cannot throw a NullReferenceException (`dr["Gender"]` null). The external `()` are not necessary though, it makes the code less readable. Less is more ;) One point though, if the asker don't want to change the state of the box if `false` : this code do it. – JoeBilly Mar 02 '15 at 11:38
0

If rbMale is the name of your radio button control, you can mark it checked by setting its Checked property to true.

rbMale.Checked = true;

bittusarkar
  • 6,247
  • 3
  • 30
  • 50