1

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

1

1 Answer 1

2

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:

enter image description here

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:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.