4

DataReaderが空の場合、コードが実行されません。以下は私のコードです。

私の仕事は日付のスケジューリングに関するものです。私の問題は、休日の制約に関するものです。ユーザーが日付 (開始日と終了日) を入力すると、プログラムは入力された日付の間に休日があるかどうかをチェックします。DataReaderにデータがない場合は、入力した日付を保存する必要がDataReaderあります。 にデータがある場合は、入力した日付は保存されず、プログラムはエラー メッセージを表示します。

try
{
    econ = new SqlConnection();
    econ.ConnectionString = emp_con;
    econ.Open();
    ecmd = new SqlCommand("SELECT CD_Date FROM CONS_DATES where CD_Date between '" + Convert.ToDateTime(dtpStart.Text) + "' and '" + Convert.ToDateTime(dtpEnd.Text) + "'", econ);
    ecmd.CommandType = CommandType.Text;
    ecmd.Connection = econ;
    dr = ecmd.ExecuteReader();
    while (dr.Read())
    {
        DateTime cdname = (DateTime)dr["CD_Date"];

        //This code is working
        if (Convert.ToDateTime(cdname) >= Convert.ToDateTime(dtpStart.Text) || Convert.ToDateTime(cdname) <= Convert.ToDateTime(dtpEnd.Text))
        {
            MessageBox.Show("Holiday Constraint. Creating Record Denied.");
        } //if

        //This code is not working. When the program fetch with no record, it should be continue to add the record but it's not working
        else
        if (dr == null || !dr.HasRows)
        {
            //In this area is my code for inserting the entered data.
            MessageBox.Show("Add na|!!!. Creating Record Denied.");
        }//if else
    }//while
}//try
catch (Exception x)
{
    MessageBox.Show(x.GetBaseException().ToString(), "Connection Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
4

5 に答える 5

10

問題は、1 つ以上のレコードがあるwhile場合にのみループが実行されることです。drただし、がの場合drnullループwhileは実行されません。

より良い解決策は、System.Data.SqlClient.SqlDataReader.

チェックして、

if (!dr.HasRows)
{
    // Your code to save the records, if no holidays found
}
else
{
    // Your code to show the error message, if there is one or more holidays
}
于 2012-10-22T03:40:38.067 に答える
0

これを試して:

while (sqlreader.Read())
{
    tbSubscriptionInfo.Text = sqlreader["nr_ore"].ToString();
}

if (!sqlreader.HasRows)
{
    tbSubscriptionInfo.Text = "";
}
于 2013-03-13T01:13:42.383 に答える
0

私は自分のアイデアを試してみましたが、それは私の質問に答えました。私がしたことは、取得したデータを datagridview に表示することでした。次に、datagridview にレコードがある場合はレコードが保存されず、datagridview にレコードがない場合はレコードが保存されるという条件を作成しました。

みんな、ありがとう!

于 2012-10-22T04:07:01.660 に答える
0

while(dr.Read())dr に少なくとも 1 つの行があることを意味します。

そうでなければ決して実行されません

しばらく前に他の条件を実行できますか?

于 2012-10-22T03:18:10.557 に答える