Skip to main content

Posts

Showing posts from 2009

Get Tables and Columns Names by LINQ

Here I am explaining one of the tricks to get all table name list along with column of it from your DataContext. I am using the System.Data.Linq.Mapping.MetaModel to get information about tables and it have much more database related information. Following are the code to list all table name along with column from your DataContext. //DataContext object. DataClassesDataContext DB = new DataClassesDataContext ();         //String variable to stor html to render. string strHtmlToLoad = "" ;         //Heading strHtmlToLoad = "<-h2->Table Names<-/h2-><-ol->" ;         //Loop through tables add name to string foreach ( var mTable in DB.Mapping.GetTables()) { strHtmlToLoad += "<-li->" + mTable.TableName + "<-ul->" ; //Loop through table's columns add name to string foreach ( var mColumn in mTable.RowType.DataMembers) strHtmlToLoad += "<-li->

Dynamic columns in Gridview

There are many types of column field are are available for grid view like BoundField ButtonField CheckBoxField CommandField HyperLinkField ImageField TemplateField Here I explain how to add dynamically Bound Field and then Template Field into grid view. First we look how to add Bound Field into Grid view and then Template Field. First of all make your AutoGenerateColumns property to false. Prepare your data source which will you going bind with grid view. it will be Data Table or Generic List of class type or structure type any thing or Table Class of your Linq dbml data contexts class. Here we are going to use Data Table as follow. DataTable dt = new DataTable ( "ItemMaster" ); dt.Columns.Add( new DataColumn ( "ItemId" , typeof ( Int32 ))); dt.Columns.Add( new DataColumn ( "ItemName" , typeof ( String ))); dt.Columns.Add( new DataColumn ( "Price" , typeof ( Decimal ))); for ( int i = 0; i < 10; i++) {    

Get website's base URL..

Following function is help you to get root path or site base URL of your web application. Like if your page URL like "http://www.blogger.com/post-create.g?blogID=5406317769839137062" this function return base URL like "http://www.blogger.com" . public static string GetApplicationPath() {      string appPath = null ;      //Getting the current context of HTTP request      HttpContext context = HttpContext .Current;      //Checking the current context content      if (context != null )      {                 //Formatting the fully qualified website url/name                 appPath = string .Format( "{0}://{1}{2}{3}" ,                 context.Request.Url.Scheme,                 context.Request.Url.Host,                 context.Request.Url.Port == 80 ? string .Empty : ":" + context.Request.Url.Port,                 context.Request.ApplicationPath);      }      return appPath; } Better One public static string GetAp

Message Panel

This in post show you how effectively you can show you messages and error regarding the user events using the Message Panel control. following are the step by step description of how to create and use Message panel. Create Message panel In your application add folder App_Code. To do that right clicking on Web project select Add Asp.net folder >> App_Code Add one class file name MessagePanel.cs and copy pest following code into it. using System; using System.Web.UI; using System.Web.UI.WebControls; namespace Controls {    // TODO: add clear link (display: none;) plus requried js    [ ToolboxData ( "<{0}:MessagePanel runat=\"server">" )]     public class MessagePanel : Panel , INamingContainer     {         private const string VSKEY_MESSAGE = "Message" ;         private const string VSKEY_ERROR = "Error" ;         bool _showMessagePanel;         bool _showErrorPanel;         string _messageCssCla

Export gridview data to csv file..

Following is the function in c# which will export passed gridview to csv file. Note that this function not work if gridview have Autogeneratedcolumn property to true, to make it dynamic you have to add column through code, how to do that see category Gridview posts. public static void ExportToCsv( string fileName, GridView gv, string Title) {             HttpContext .Current.Response.Clear();             HttpContext .Current.Response.AddHeader( "content-disposition" , string.Format( "attachment; filename={0}" , fileName));             HttpContext .Current.Response.ContentType = "application/ms-excel" ;             using ( StringWriter objSw = new StringWriter ())             {                 //  Create a table to contain the grid                 Table table = new Table ();                 //  include the gridline settings                 table.GridLines = gv.GridLines;                 objSw.Write( "Report:  " + Title +

Disable submit on return keypress..

Following are the code to disable enter key or return key submit behaviour of Asp.net page. Override page OnInitComplete event and add this code. protected override void OnInitComplete( EventArgs e) {            base.OnInitComplete(e);            string script = "function DisableEnterKey(){" +                                  "if(event.keyCode == 13){return false;}" +                                  "else{return true;}}" ;            Page.ClientScript.RegisterStartupScript( this .GetType(), "page" , script, true );            Page.Form.Attributes.Remove( "onkeypress" );            Page.Form.Attributes.Remove( "onkeydown" );            Page.Form.Attributes.Add( "onkeypress" , "return DisableEnterKey()" );            Page.Form.Attributes.Add( "onkeydown" , "return DisableEnterKey()" ); }

XML data access through Linq..

Following are the setp to read data from XML file using linq query 1st : Add following name spaces by using using System.Xml; using System.Xml.Linq; 2nd : Create XDocument object and load XML file XDocument objXDocument = XDocument.Load(Server.MapPath( "~/App_Data/XYZ.xml" )); 3rd : Write following linq query to read data from XDcument object var q = from c in loaded.Descendants( "Iteams" )                     select c.Elements( "Item" ); You can also specify where condition like following var q = from c in loaded.Descendants( "Items" )                     where c.Attribute( "id" ).Value = "id1"                     select c.Elements( "Item" ); 4th : Check for null and then convert var object 'q' to List List < XElement > objElem = q.ToList()[0].ToList(); Following is the structuer of the XML file used for this code <? xml version ="1.0" encoding

Ordering columns of GridView by code..

Following are the step to change order of your grid view column by code.. 1st : make DataControlFieldCollection clone to your gridview columns DataControlFieldCollection gvdcfCollection = grid.Columns.CloneFields(); 2nd : clear the grid columns grid.Columns.Clear(); 3rd : Itreate through the clone copy and based on logic add or insert DataControlField   into grid columns collection grid.Columns.Add( gvdcfCollection[0] );  or grid.Columns.Insert(0, gvdcfCollection[0] ); Note: If you have template column in your grid view then you have to make EnableViewState property of  grid view to false.