Friday, September 5, 2008

HowTo: Display a radiobuttonlist with images





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RadioListImage.aspx.cs" Inherits="RadioListImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <asp:RadioButtonList ID="rdoI" runat="Server">
          </asp:RadioButtonList>
      </div>
  </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class RadioListImage : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       string[] strImages = System.IO.Directory.GetFiles(Server.MapPath("~/img"));

       foreach (string strImage in strImages)
       {
           this.rdoI.Items.Add(new ListItem(String.Format("<img src='{0}'>", strImage.ToString()), strImage.ToString()));
       }
   }
}

2 comments:

Anonymous said...

Hi, nice post, thanks so much.

I am facing little problem that Directory.GetFiles returns paths with thier files according to this msdn reference http://msdn.microsoft.com/en-us/library/wz42302f.aspx so i trimed it.

Please Remove the text (--RemoveThisText--) from code
Changed Code --------------------------
string[] strImages = System.IO.Directory.GetFiles(Server.MapPath("~/img"));

foreach (string strImage in strImages)
{
string FileNamesOnly = strImage.Remove(0, strImage.LastIndexOf('\\') + 1);
this.rdoI.Items.Add(new ListItem(String.Format("<--RemoveThisText-- img src='img/{0}'>", FileNamesOnly.ToString()), strImage.ToString()));
}

may this helps others
Thanks Asim

santosh said...

@Asim:Thanks...

Post a Comment