数据库为空时显示消息框

时间:2016-01-02 19:03:18

标签: c# sql database forms messagebox

感谢您查看我的问题。基本上,当用户点击某个按钮时,它会根据数据库的内容在消息框中说出以下内容之一:您的假期已被授权,您的假期已被拒绝或您的假期请求已被发送。

我想要它,以便当用户点击按钮并且数据库中没有任何数据因为用户没有发送假日请求时,接收一个消息框,说明他们没有预订假期

这是我的代码:

            private void button2_Click_1(object sender, EventArgs e)
    {
        System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["Login"];
        SundownDatabaseEntities6 db = new SundownDatabaseEntities6();
        int id = Convert.ToInt32(((Login)f).idTb.Text);

        var getrecords = db.Holidays.Where(a => a.Id == id).ToList();

            foreach (var record in getrecords)
            {
                if (record.YesOrNo == "yes")
                {
                    MessageBox.Show("The manager has accepted your holiday (From " + record.Datefrom + " - " + record.Dateto + ").");
                }
                else if (record.YesOrNo == "no")
                {
                    MessageBox.Show("The manager has declined your holiday request (" + record.Datefrom + " - " + record.Dateto + ").");
                }
                else if (record.YesOrNo == null)
                {
                    MessageBox.Show("Your holiday request (" + record.Datefrom + " - " + record.Dateto + ") has been sent.\nWaiting for manager to authorise it...");
                }
                else if (record != null)
            {
                MessageBox.Show("You have not booked an holiday.");
            }
            }
        }

问题出现在代码的最后一位,'else if(record!= null)'不检查数据库是否为空。有什么建议?谢谢!

1 个答案:

答案 0 :(得分:0)

您应该检查getrecords.Count()

var getrecords = db.Holidays.Where(a => a.Id == id).ToList();
if (getrecords.Count() == 0) 
{
 //  ... here your logic
}

if (!db.Holidays.Any ())

因为如果foreach为空,它将不会转到getrecords