简体   繁体   中英

getting image from database and display in the webform using asp.net

I have a table with id,name,gender,picture in sql database.I have a form to display all of these fields. when i click on getstudentById button i should be able to display all the fileds including image. I am able to write code to display all the fields except image. can someone please help me to write code for that in c#.net.

Thank you

Ok, so say we drop in a some text boxes (FirstName, LastName, City), and then also a Picture onto the web page.

We have this mark up:

在此处输入图像描述

Ok, dead simple.

Now, code to set the text boxes and image from the database?

Like this:

protected void Button1_Click(object sender, EventArgs e)
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM PeopleP WHERE ID = 2", 
                          new SqlConnection(My.Settings.TEST4)))
  {
    cmdSQL.Connection.Open();
    DataTable MyTable = new DataTable();
    MyTable.Load(cmdSQL.ExecuteReader);
    DataRow MyRow = MyTable.Rows(0);

    txtFirst.Text = MyRow("FirstName");
    txtLast.Text = MyRow("LastName");
    txtCity.Text = MyRow("City");

    Image1.ImageUrl = "data:image/gif;base64," + Convert.ToBase64String(MyRow("Picture"));
}
}

I VERY strong suggest that when you add rows to the sql server table, you save the "mine" type. In above I hard coded this example (gif), but you REALLY need to save that file type when you add the rows to sql server.

And I could have saved a line or 2 of code by not using a DataRow, but it just made the refercing of columns somewhat cleaner.

You can of course use:

MyTable.Rows(0).item("FirstName")

but, I splurged here and figured the developer cost and time of the extra line of code and using a row just seems to result in cleaner code and ease of referencing the columns in the database.

You can get the mine type with this:

Web.MimeMapping.GetMimeMapping(strFullFilePath)

So in place of the hard coded gif, then we have/get this:

"data:" + MyRow("WebContentType") + ";base64," + Convert.ToBase64String(MyRow("Picture"));

So, you would do well to have saved the file type into the database if all pictures types are to be allowed. As noted, the example I used above hard coded the type as ".gif". If all picture types are to be the same - not a big deal. However, if you wish to support many different types of images - then save the mine type as a column in the database, and as per above you thus not have hard coded to one picture type.

After running above code, I get this result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM