private void Page_Load(object sender, System.EventArgs e) { // ページを初期化するユーザー コードをここに挿入します。 // パネルをとりあえず両方非表示にする Panel_Success.Visible = false; Panel_Error.Visible = false; ErrorMessage.Text = ""; // 商品IDを取得する int productid; try { productid = int.Parse(Request.QueryString["ID"]); } catch (Exception ex) { if (ex is ArgumentNullException) { // 商品IDが指定されていない Panel_Error.Visible = true; ErrorMessage.Text = "商品番号が指定されていません"; } else if (ex is FormatException || ex is OverflowException) { // 商品IDの値が不正 Panel_Error.Visible = true; ErrorMessage.Text = "商品番号が不正です"; } else { // その他のエラー Panel_Error.Visible = true; ErrorMessage.Text = "不明なエラーです"; Response.AppendToLog(ex.Message); } return; } // データベースに接続して該当のレコードを得る SqlConnection sqlconn = new SqlConnection(ConfigurationSettings.AppSettings["DSNSTRING"]); // SELECT文を送信するSqlCommandオブジェクトを用意する SqlCommand sqlcmd = new SqlCommand( "SELECT id, productname, price, stock, comment, detail, DATALENGTH(imgdata) As imglength, createdate, lastupdate FROM Products" + " WHERE id=@id", sqlconn); // パラメータを設定する sqlcmd.Parameters.Add("@id", SqlDbType.Int).Value = productid; // 実行する SqlDataReader sqlreader = null; try { // 接続を開く sqlconn.Open(); // SELECT文を実行する sqlreader = sqlcmd.ExecuteReader(); // レコードの値を取得する if (sqlreader.Read()) { // レコードが存在する // ラベルなどに、実際の値を設定する ProductNameLabel.Text = Server.HtmlEncode(sqlreader.GetString(1)); CreatedateLabel.Text = Server.HtmlEncode(string.Format("登録日 {0:yyyy/MM/dd}", sqlreader.GetDateTime(7))); LastupdateLabel.Text = Server.HtmlEncode(string.Format("最終更新日 {0:yyyy/MM/dd}", sqlreader.GetDateTime(8))); switch (sqlreader.GetInt32(3)) { case 0: StockLabel.Text = "在庫なし"; break; case 1: StockLabel.Text = "在庫あり"; break; case 2: StockLabel.Text = "在庫僅少"; break; case 3: StockLabel.Text = "在庫要問い合わせ"; break; default: StockLabel.Text = "在庫不明"; break; } PriceLabel.Text = Server.HtmlEncode(string.Format("価格{0:c}", sqlreader.GetDecimal(2))); DetailLabel.Text = Server.HtmlEncode(sqlreader.GetString(5)).Replace("\n", "
"); // 画像の処理 if (sqlreader.IsDBNull(6) || sqlreader.GetInt32(6) == 0) { // 画像なし NoImageLabel.Text = "画像がありません"; ProductImage.Visible = false; } else { // 画像あり NoImageLabel.Visible = false; ProductImage.ImageUrl = string.Format("productimage.aspx/{0}.jpg", productid); } // 成功した旨のパネルを表示 Panel_Success.Visible = true; } else { // レコードが存在しない ErrorMessage.Text = "該当の商品がありません"; Panel_Error.Visible = true; } } catch (SqlException ex) { // エラーが発生した Response.AppendToLog(ex.Message); ErrorMessage.Text = "申し訳ございません。データベースエラーのため処理を完了できませんでした"; Panel_Error.Visible = true; } finally { // 接続を閉じる if (sqlreader != null) { sqlreader.Close(); } sqlconn.Close(); } }