December 30, 2014

Load XML in a GridView using Asp.Net

Xml files can be loaded into a GridView control in asp.net. To load xml files, it can be usually binded to the GridView by creating the xml data source and then setting the data source property of the GridView. However, if xml files contains nodes, then it does not work and instead produces error -

The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

To bind the xml file with nodes, it's easier to create a dataset and then to bind it to the gridview from code behind. Here is an example of how that would work.

Sample Xml File
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Customers>
  3.   <Customer>
  4.     <Id>C1</Id>
  5.     <Name>John</Name>
  6.     <DateOfBirth>9 Jan 1960</DateOfBirth>
  7.     <Phone>99999999</Phone>
  8.     <Address>Canberra</Address>
  9.   </Customer>
  10.   <Customer>
  11.     <Id>C2</Id>
  12.     <Name>Smith</Name>
  13.     <DateOfBirth>10 August 1980</DateOfBirth>
  14.     <Phone>88888888</Phone>
  15.     <Address>Sydney</Address>
  16.   </Customer>
  17.   <Customer>
  18.     <Id>C3</Id>
  19.     <Name>Peter</Name>
  20.     <DateOfBirth>12 June 1978</DateOfBirth>
  21.     <Phone>77777777</Phone>
  22.     <Address>Melbourne</Address>
  23.   </Customer>
  24. </Customers>

 

aspx page
  1.     <div>
  2.     <asp:GridView ID="GridView1" runat="server">
  3.     </asp:GridView>
  4. </div>

 

Code to bind xml to gridview
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     if (!IsPostBack)
  4.     {
  5.         DataSet ds = new DataSet();
  6.         ds.ReadXml(MapPath("~/App_Data/data.xml"));
  7.         GridView1.DataSource = ds;
  8.         GridView1.DataBind();
  9.     }
  10. }

December 17, 2014

Properties of uploaded image

Asp.net provide option to upload files like images using FileUpload control but how can we find out certain properties of the image like file size and dimensions. In this post, I will show how to find those properties.

First, in the design view, I got a FileUpload control and a Button. The image will be uploaded when the button is clicked.

  1. <div>
  2.     <asp:FileUpload ID="fu1" runat="server" />
  3.     <asp:Button ID="b1" runat="server" Text="Save" OnClick="b1_Click" />
  4. </div>


In the code-behind, I am using System.Drawing.Image to get image dimension and ContentLength property to get the file size as shown below.

  1. protected void b1_Click(object sender, EventArgs e)
  2. {
  3.     System.Drawing.Image img = System.Drawing.Image.FromStream(fu1.PostedFile.InputStream);
  4.     double height = img.Height;
  5.     double width = img.Width;
  6.  
  7.     double filesize = fu1.PostedFile.ContentLength / 1024;
  8.  
  9.     //do something with the values
  10. }
Reference: Shahed Kazi at AspNetify.com