简体   繁体   中英

Get radio button value

I have tried to get radio button values from windows store application form but its showing errors as follows, and im using visual studio 2013 and XAML.

private void addButton_Click(object sender, RoutedEventArgs e)
{
  try
  {
    string gender = null;
    if (maleRadioButton.IsChecked || femaleRadioButton.IsChecked)
    {
      gender = maleRadioButton.Checked ? "Male" : "Female";
    }

    string Query = @"INSERT INTO `bcasdb`.`tbl_student`
                   (`reg_id`,
                   `std_fname`,
                   `std_lname`,
                   `tbl_batch_batch_id`,
                   `gender`) 
                   VALUES (@regId, @fName, @lName, @bID, @gender)";

    //This is command class which will handle the query and connection object.
    MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
    MySqlCommand cmd = new MySqlCommand(Query, conn);
    conn.Open();
    cmd.Parameters.AddWithValue("@regId", this.regIDInput.Text);
    cmd.Parameters.AddWithValue("@fName", this.fnameInput.Text);
    cmd.Parameters.AddWithValue("@lName", this.lnameInput.Text);
    cmd.Parameters.AddWithValue("@bID", this.batchIDInput.Text);
    cmd.Parameters.AddWithValue("@gender",this.maleRadioButton);
    cmd.ExecuteNonQuery();
    conn.Close();
    successmsgBox();
  }
  catch (Exception)
  {
    errormsgBox();
  }
}

this part has errors

string gender = null;
if (maleRadioButton.IsChecked || femaleRadioButton.IsChecked)
{
  gender = maleRadioButton.Checked ? "Male" : "Female";
}

RadioButton.IsChecked property is not [bool], its type is [bool?].

So you cannot use just if-sentence.

You can set specific boolean variable for radiobutton's checked flag.

bool isMale = false;
bool isFemale = false;

and then,

private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
   isMale = sender == maleRadioButton;
   isFemale = sender == femaleRadioButton;
}

of course, maleRadioButton and femaleRadioButton has checked event handler.
like,

<RadioButton x:Name="maleRadioButton" checked="RadioButton_Checked" />
<RadioButton x:Name="femaleRadioButton" checked="RadioButton_Checked" />

then, you can use as follow.

string gender = null;
if (isMale || isFemale)
{
  gender = isMale ? "Male" : "Female";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM