Friday, April 23, 2010

Regular Expression for mm/dd/yyyy

Regular Expression which accepts mm/dd/yyyy format is

\b(0?[1-9]|1[0-2])(\/)(0?[1-9]|1[0-9]|2[0-9]|3[0-1])(\/)([1-9][0-9][0-9][0-8])\b

Valid Formats:

1/2/2005
12/28/2006
12/12/2099

Wednesday, April 14, 2010

Adding Mulitple Columns to a List Box in ASP.Net


Adding Mulitple Columns to a List Box in ASP.Net

Generally we dont add multiple columns in a Listbox. But if there is a requirement (which i found out as challenging) then keep that it mind, i am posting this article. Hope this might help not all of them but atleast some people.

Here is the screen shot of the ASP.Net List Box with mutiple column with proper alignment

====================
Name Id
====================
Prashanth, Kumar    740
Agarwal, Kajal        735
Barnes, Candas       569
Deja, Stephanie       9
Bartely, Adam         12
---------------------------------
Follow the code below by creating a webpage with a listbox and configure your database connection string in web.config

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox1.Items.Clear();
DataTable dt = new DataTable();
dt = GetNames();
int maxLength = FindTheLargestName(dt);

foreach (DataRow dr in dt.Rows)
{
string fullName = dr["LastName"].ToString() + ", " + dr["FirstName"].ToString();

ListItem li = new ListItem(fullName.PadRight(maxLength + 3, Convert.ToChar(160)) + dr["Id"].ToString().Trim(), dr["Id"].ToString().Trim());
ListBox1.Items.Add(li);
}
}
}

Utitlity Functions Required

// This returns id firstname last name and address
public DataTable GetNames()
{
DataTable dt=new DataTable();

using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("select * from ractable", con))
{

using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
adap.Fill(dt);
}
}
}
return dt;
}

public static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["YourConnectionStringFromWeb.Config"].ConnectionString;
}

public int FindTheLargestName(DataTable dt)
{
string name=string.Empty;
int sLength = 0;
foreach (DataRow dr in dt.Rows)
{
name = dr["Fname"].ToString() + dr["Lname"].ToString();
//name = dr["Name"].ToString();
if (name.Length > sLength)
sLength = name.Length;
}
return sLength;
}

Just follow these steps that should fine.

NOTE:
Important thing to do in this process is to change the font name of the list box to either “Courier New” or “Lucida Console” as these are Monospaced fonts. This works only with monospaced fonts.