获取单选按钮值

时间:2014-10-10 15:11:55

标签: c# mysql wpf radio-button

我试图从Windows商店应用程序表单中获取单选按钮值,但是它显示如下错误,并使用visual studio 2013和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();
  }
}

此部分有错误

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

1 个答案:

答案 0 :(得分:0)

RadioButton.IsChecked属性不是[bool],它的类型是[bool?]。

所以你不能只使用if-sentence。

您可以为radiobutton的checked标志设置特定的布尔变量。

bool isMale = false;
bool isFemale = false;

然后,

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

当然, maleRadioButton femaleRadioButton 检查了事件处理程序。
等,

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

然后,你可以使用如下。

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