从sql数据库检索空值和其他值到文本框

时间:2013-02-03 18:08:58

标签: c# visual-studio-2010 sql-server-2008

我在Visual Studio中从SQL数据库中检索值时遇到问题。我在GUEST表中有列(GuestName,GuestPassportNo,GuestCountry,RoomID,HotelPackageID),其中HotelPackageID包含NULL值,而其余值包含值。当HotelPackageID为NULL时,我总是被抛入else语句(没有找到记录)。有人有解决方案吗?这是我的代码:

SqlConnection myConnect = new SqlConnection(strConnectionString);

string strCommandText = "SELECT Guest.GuestPassportNo, 
                                Guest.GuestName,   
                                Guest.GuestCountry, 
                                Guest.RoomID, 
                                Room.RoomDescription, 
                                Room.RoomPrice, 
                                HotelPackages.PackageName, 
                                HotelPackages.PackagePrice ";

strCommandText += " FROM Guest, Room, HotelPackages";

strCommandText +=" WHERE Guest.RoomID=Room.RoomID 
                   AND Guest.GuestPassportNo=@guestpno 
                   AND HotelPackages.PackageID=Guest.HotelPackageID 
                   AND Guest.GuestCountry=@guestcountry;

SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("@guestpno", txtPassportNo.Text);
cmd.Parameters.AddWithValue("@guestcountry", txtGuestCountry.Text);

try
{
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();

if(reader.Read())
{
txtGuestName.Text = reader["GuestName"].ToString();
txtRoomDescription.Text = reader["RoomDescription"].ToString();
txtRoomPrice.Text = reader["RoomPrice"].ToString();
txtHotelPackage.Text = reader["PackageName"].ToString();
txtPackagePrice.Text = reader["PackagePrice"].ToString();
MessageBox.Show("Guest Record Found!");
}

else
{
Messagebox.Show("No record Found");
}

reader.Close();
}

catch(Exception ex)
{
MessageBox.Show(ex.message);
}

finally
{
myConnect.Close();
}

1 个答案:

答案 0 :(得分:2)

您需要更改查询:

strCommandText +=" WHERE Guest.RoomID=Room.RoomID AND Guest.GuestPassportNo=@guestpno AND HotelPackages.PackageID=Guest.HotelPackageID AND Guest.GuestCountry=@guestcountry;

应该是:

strCommandText +=" WHERE Guest.RoomID=Room.RoomID AND Guest.GuestPassportNo=@guestpno AND (HotelPackages.PackageID=Guest.HotelPackageID OR GUEST.HotelPackageID IS NULL) AND Guest.GuestCountry=@guestcountry;