简体   繁体   English

如何修复单选按钮不显示消息框

[英]How to fix radio button not showing message box

I want to make radio button and when I click button save and then my radio button not selected it can appear some message box.我想制作单选按钮,当我点击按钮保存然后我的单选按钮未被选中时,它会出现一些消息框。

 private void btnSimpan_Click(object sender, EventArgs e) { try { DataPembeli p = new DataPembeli(); p.Pembeli = txtPembeli.Text; p.AlamatKirim = txtAlamat.Text; p.Kuantitas = (int)kuantitasItem.Value; p.TglPesan = dtTglPesanan.Value; p.HasAsuransi = chkAsuransi.Checked; p.ItemOrdered= cmbItem.Text; foreach (Control c in grpbxMetodePengiriman.Controls) { if (c is RadioButton) { RadioButton rb = (RadioButton)c; if (rb.Checked) { p.MetodePengiriman = rb.Text; break; } } else { p.MetodePengiriman = "0"; break; }

You appear to be saying that you want to make sure that the user has checked a RadioButton in a group.您似乎是在说您要确保用户已选中组中的RadioButton If so, the best way is to use LINQ to get all the RadioButtons in the container and see if any are checked, eg如果是这样,最好的方法是使用 LINQ 获取容器中的所有RadioButtons并查看是否选中任何内容,例如

if (myContainer.Controls.OfType<RadioButton>().Any(rb => rb.Checked))
{
    // A RadioButton in myContainer has been checked.
}

If you actually want to get the checked RadioButton and use it then you can do this:如果您真的想获得选中的RadioButton并使用它,那么您可以这样做:

var checkedRadioButton = myContainer.Controls.OfType<RadioButton>().FirstOrDefault(rb => rb.Checked)

if (checkedRadioButton == null)
{
    // No RadioButton is checked.
}
else
{
    // Use checkedRadioButton here.
}

Based on your code, you could probably do this:根据您的代码,您可能会这样做:

p.MetodePengiriman = myContainer.Controls
                                .OfType<RadioButton>()
                                .FirstOrDefault(rb => rb.Checked)
                                ?.Text ?? "0";

FirstOrDefault will either return a RadioButton reference or null . FirstOrDefault将返回RadioButton引用或null If the former, the Text property of that control will be used.如果是前者,将使用该控件的Text属性。 If the latter, the ?.如果是后者, ?. operator will cause the whole expression to evaluate to null and then the "0" will be used instead.运算符将使整个表达式的计算结果为null ,然后将使用"0"代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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