【问题标题】:How to change this code to receive only one msgbox?如何更改此代码以仅接收一个 msgbox?
【发布时间】:2016-12-19 05:12:53
【问题描述】:

我有带有复选框的 datagridview 列。我想检查此列中是否有选定的行。如果不是,我想显示 msgbox。我可以通过这个检查列,但我收到每个未选中行的多个 msgbox。怎么改成只接收一个msgbox?

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewCheckBoxCell cell = row.Cells[5] as DataGridViewCheckBoxCell;

    //We don't want a null exception!
    if (cell.Value == null)
    {
        MessageBox.Show("Nie zaznaczono pola!");
    }
}

编辑:

谢谢你的回答。我意识到我的问题比我想象的要复杂。我的按钮必须从数据网格中删除选定的行。问题出在 foreach 上,因为它只删除第一行,并且在我使用 if/else 时仍然显示 msgbox。我需要删除数据,如果没有选中复选框,请执行 msgbox。这是我的按钮:

private void button2_Click(object sender, EventArgs e)
{
    con.Open();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        object cell = row.Cells["cell_del"].Value;
        if (cell == "yes")
        {

            SqlCommand cmd = new SqlCommand("Delete From Rok2016 where ID ='" + row.Cells[4].Value.ToString() + "'", con);
            cmd.ExecuteNonQuery();

            wczytywanie_tabeli();
        }

        else 
        {                               
            MessageBox.Show("Nie zaznaczono pola!");
            break;
        }
    }




    con.Close();
}

【问题讨论】:

    标签: c# checkbox datagridview


    【解决方案1】:

    您可以在获得空值后停止循环,只需在找到空值时中断循环即可:

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell cell = row.Cells[5] as DataGridViewCheckBoxCell;
    
        //We don't want a null exception!
        if (cell.Value == null)
        {
            MessageBox.Show("Nie zaznaczono pola!");
            break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 2023-03-20
      • 2018-02-22
      • 1970-01-01
      相关资源
      最近更新 更多