pictureBox
インターネットから直接画像を読み込むがあります。画像は動的に変更でき、画像を の URL に変更するイベントをtextBox
持つ でユーザーによって指定されます。ユーザーが送信ボタンをクリックすると、画像の URL がデータベースに保存されます。しかし、保存する前に、画像が正常に表示されたか、エラー画像が代わりに表示されたかを検証したいと思います。では、どうすればこれを検証できますか?TextChanged
pictureBox
textBox
3 に答える
LoadComplete イベントを使用して、いつ変更されたか、および eventArg のエラーが null (成功) か null でない (失敗) かを確認できます。
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show(e.Error.ToString());
}
this.pictureBox1.Validated += new EventHandler(pictureBox1_Validated);
this.pictureBox1.ImageLocation = this.textBox1.Text;
-編集:Dipsのコメントを見ただけで、そのリンクは使用しませんでしたが、これに答えるのと同じ手段です。
textBox から画像のパスを取得する関数に以下のコードを配置します。そのパスで他の操作を行う前に配置してください。
string path = "Path to image";
Bitmap bmp;//To validate the Image.
try
{
bmp = new Bitmap(path);//Create a Bitmap object from the given path.
if (bmp != null)
{
pictureBox1.Load(path);//Display the image to the user.
//Now it's safe to store the image path in the database,
//because we have validated it.
bmp.Dispose();//Dispose the Bitmap object to free occupied resources.
//Place you database related code here which uses the path we just validated.
}
}
catch (ArgumentException)
{
MessageBox.Show("The specified image file is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
catch (FileNotFoundException)
{
MessageBox.Show("The path to image is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
これが完了したら、//Place your database...というコメントが表示されている場所にコードを配置できます。画像ファイルは実際には画像であり、拡張子が.jpgまたはその他の画像形式に変更された.txtまたは.exeではありません。コメントで述べたように、パスが実際に画像ファイルを指しているかどうかを確認する必要があります。
MessageBox
エラー情報を表示する以上のことが必要な場合は、例外処理メカニズムを拡張できます。before you display any image or do anything you will have to check if the url is valid one,to simplify this step you can try to download the file(it can be anything - an image,an executable,a text file or at least a web page,when it has been downloaded pass the path to that file(relative to filesystem) to this function.
それがうまくいくことを願っています。