GridView Pagination issue when dynamically added….!

Posted on Updated on

Hello ASP.NET Developers… Today I came across a small issue which killed large amount of my development time. The issue was a little tricky between the lines of code. I have an ASP.NET gridview which is dynamically (on the fly) created on my page. When I am inserting 2 lines of code  just for allowing the gridview pagination, code breaks at runtime giving  a NullReferenceException .

Cause of the issue :  i was adding the dynamically created  gridview(object) into page’s control collection after the databinding. This works fine if there is no pagination code added. But if there is code which allows pagination for the dynamically added gridview, this gridview should be added to the page’s control collection before the databinding.

Please see the below mentioned code blocks for the difference.

This piece of code will give the Null Reference Exception:

GridView gvDepartment = new GridView ();
gvDepartment.ID = "gvDepartment";

gvDepartment.AllowPaging = true;
gvDepartment.PageSize = 4;

gvDepartment.DataSource = GetDepartmentRows ();
gvDepartment.DataBind ();

this.form1.Controls.Add ( gvDepartment );

This is the perfect code:

        GridView gvDepartment = new GridView ();
        gvDepartment.ID = "gvDepartment";

        gvDepartment.AllowPaging = true;
        gvDepartment.PageSize = 4;

	/* Need to add gridview into controls collection before databind,if there is pagination */
        this.form1.Controls.Add ( gvDepartment );

        gvDepartment.DataSource = GetDepartmentRows ();
        gvDepartment.DataBind ();

NB: Obviously PageIndexChanging Event handling is needed. But this post is about the exception thrown while dynamically adding gridview. So the readers please keep in mind to add pageindexchanging event should be handled.
I hope this post helped you or given a nice thought. Thanks for reading.Please comment if you feel any issues on the same.

How to send XML data to a Webpage using “POST” Method.

Posted on Updated on

Recently I came across an interesting requirement to send XML data to a particular URL using POST, means i need to post some XML data to a URL. I came to answer within a couple hrs of “googling” and R&D. Below mentioned is the sample code that I have created to explain the technique. Scenario defines here explains data sending between 2 websites, one is requestor website, which send xml POST data and other is responder website, which collect data from requestor website.

The step by step instructions are as follows.

  1. Open a Microsoft Visual Studio instance and from the file menu select the option to create ASP.NET website/web application. Create two websites using this option and name these websites with user-friendly names such as Requestor and Responder. For easier developer view make these websites under a single visual studio solution.
  2. By default there will be a default.aspx page inside each website. Just delete that page, we can create new pages for our sample
  3. Add a new page to the Requestor website. We can name this page as requestor.aspx. Our aim is to post XML data from requestor.aspx to the responder.aspx of the Responder website. Using the responder page we will save that XML data to a text (.txt) file. Add a new page to the Responder website name this page as requestor.aspx.
  4. Host Responder website on your local IIS.
  5. Select the Requestor website. Design the Requestor page as shown on the image below.

Page design of the Requestor page
One main Multiline textbox for XML Data, a Textbox for entering  URL to send the XML data and  a Button

6.Handle the click event of the button, add the following the piece of code to that event.

protected void btnPostXml_Click(object sender, EventArgs e)
{
        System.Net.WebRequest req = null;
        System.Net.WebResponse rsp = null;
        try
        {
            string uri = txtURI.Text;
            req = System.Net.WebRequest.Create ( uri );
            req.Method = "POST";
            req.ContentType = "text/xml";
            System.IO.StreamWriter writer = new System.IO.StreamWriter ( req.GetRequestStream () );
            writer.WriteLine (  txtXMLData.Text );
            writer.Close ();
            rsp = req.GetResponse ();
        }
        catch
        {
            throw;
        }
        finally
        {
            if (req != null) req.GetRequestStream ().Close ();
            if (rsp != null) rsp.GetResponseStream ().Close ();
        }
}

7.Select the Responder website. Take the Page Load event of the Responder.aspx page. Add the following piece of code to the Load event.

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Response.ContentType = "text/xml";
        System.IO.StreamReader reader = new System.IO.StreamReader ( Page.Request.InputStream );
        String xmlData = reader.ReadToEnd ();
        System.IO.StreamWriter SW;
        SW = File.CreateText ( Server.MapPath(".")+@"\"+ Guid.NewGuid () + ".txt" );
        SW.WriteLine ( xmlData );
        SW.Close ();
    }

Here we are reading the stream of data from the page request and writing that data to a text file.
Note: On this sample i have made the ValidateRequest=”false” for the requestor to accept the XML Data on the form post.

This methodology can also be used as a CALLBACK to a URL with some data post.

Take the code sample(VS 2010 needed)

Thanks for reading this post. Please comment if you have any issues/doubt with the code.

WebControl/Custom Control’s events not working?.

Posted on Updated on

Few days back i had a strange issue during my webcontrol development .The issue was that child control events like button click’s , DropDownlist’s  SelectedIndexChanged are not working. On a simple glance everything  was done as per the regular flow of coding… I search on Bing,Live,Google etc…. Didnt find much effective solution on the first day.. On a deep dive to webcontrol development i found some articles,books,blogs that  mentioning about the influence of implementation INamingContainer interface to the WebControl Class. Actually this interface does nothing when we do the implementation . Means we except must implemented functions from the interface. But in case INamingContainer there is nothing like that… its  a marker interface.By this interface it allows unique naming of the dynamically generated server control instances within the WebControl.       

Here i will explain the creation of a simple webcontrol. So  HOW  TO CREATE  A  WEBCONTROL?         

 1. Open Visual Studio and  Create a blank solution.(File menu –> New Project –> On left side Project Types tree, expand Other Project Types node, select Visual Studio Solutions, Select Blank Solution from right side pane.). Name the Solution  as WebControls         

2.Add a Class library Project to this solution.Name this as WebControlAssembly.       

 3.Add  the Reference of System.Web to the library. This reference is done  to get the System.Web.UI.WebControls, System.Web.UI namespaces inside the project.         

4.Rename the default added Class file to TextButtonControl.cs.         

5. Delete all the default code from the new class file and paste the below mentioned lines of code to the class file.         

using System;
using System.Web.UI;
using System.Web.UI.WebControls; 
namespace TextButtonWebControl
{
 //*** INamingContainer is a must.Any control that implements this interface creates a new namespace in which all child control ID-
 //attributes are guaranteed to be unique within an entire application.
 //The marker provided by this interface allows unique naming of the dynamically generated server control instances within the-
 //Web server controls that support data binding
 public class TextButtonControl : WebControl, INamingContainer
 {
  private TextBox txtControl;
  private Button btnControl;
  private Table tbl;// Master container of button and textbox.   

  //public event for handling click  of the button
  public event EventHandler BtnClick;   

  public TextButtonControl()
  { }   

  protected override void CreateChildControls()
  {     

   txtControl = new TextBox();
   txtControl.ID = "txtControl";   

   btnControl = new Button();
   btnControl.ID = "btnControl";
   btnControl.Text = "Submit";
   btnControl.CausesValidation = false;
   btnControl.Click += new EventHandler(btnControl_Click);   

   tbl = new Table();
   tbl.Width = Unit.Percentage(25);
   tbl.ID = "tbl";   

   TableRow tblrow = new TableRow();
   tblrow.ID = "tblrow";
   tblrow.Width = Unit.Percentage(100);   

   TableCell tblCell0 = new TableCell();
   tblCell0.ID = "tblCell0";
   tblCell0.Controls.Add(txtControl);
   tblCell0.HorizontalAlign = HorizontalAlign.Left;   

   TableCell tblCell1 = new TableCell();
   tblCell1.ID = "tblCell1";
   tblCell1.HorizontalAlign = HorizontalAlign.Left;
   tblCell1.Controls.Add(btnControl);   

   tblrow.Cells.Add(tblCell0);
   tblrow.Cells.Add(tblCell1);
   tbl.Rows.Add(tblrow);
   Controls.Add(tbl);   

   base.CreateChildControls();
  }   

  //Button Click event to call public event.
  void btnControl_Click(object sender, EventArgs e)
  {
   this.ControlText = txtControl.Text;
   if (BtnClick != null)
   {
    BtnClick(sender, e);
   }   

  }   

  public string ControlText
  { get; set; }   

 }
}   

    6. Just compile the Class the library project. Build Succeeded…….! ???. Webcontrol is ready now…..           

 7. In this step we will add a New Website to this solution. Right click on the newly created website , click Add reference option and on the Add reference window click  Projects tab . On this tab select Webcontrol Library project, here in this example it is WebControlAssembly. Click OK. The reference of the Webcontrol is added to website. Now we can add the webcontrol to the webpage.Follow this register tag  to  register this control to page  .  <%@ Register Assembly=”WebControlAssembly” Namespace=”TextButtonWebControl” TagPrefix=”Tc” %>           

This  mark-up will add the control to the page. You can see the custom event “OnBtnClick” to handle the button click of the  WebControl.         

<Tc:TextButtonControl ID=”TextButtonControl1″ runat=”server” OnBtnClick=”TextButtonControl1_BtnClick” />  
 Below mentioned is event handling for the OnBtnClick Event.    

 protected void TextButtonControl1_BtnClick(object sender, EventArgs e)  

   Response.Write(TextButtonControl1.ControlText); }    

 Please read the step 8 to get the proper understanding of code.      

  

 8.  I will explain the above piece of code . This webcontrol is intended to create a small  table layout which have a TextBox and Button. The TextButtonControl class is inherited from WebControl and it also implementated INamingContainer. The reason for this interface implemenatation  is mentioned on the top of the post. The CreateChildControls method is overrided to create the instances of the child controls like button,textbox,Table and to control collection. Here Table is the master container for the button and textbox to maintain the layout of the webcontrol. The button and texbox is added to the Table’s object instance and Table’s object instance is added to the Control Collection.Please check the CreateChildControls method for the code.      We have handled the button’s click event and this event can be  handled from webpage where this control is used.There is a public event called BtnClick which is called on the button’s click event and event is raised from webpage. This is very useful to handle the child control event from the webpage where the webcontrol is used.       

  There is ControlText get-set property to get or to set the Text value of the Textbox Control of the webcontrol.Using this property we can receive the text value from the textbox of the webpage where the control is  used.      

Hope this artice helped you…  if any suggestions or feedback please leave a comment.Thanks for reading.   

  

      

    

 

   

  

Pulikali….! – its a word that a guy from Thrissur cant forget

Posted on Updated on

Pulikali : PULI means TIGER/Cheetah; KALI means play – This play used to conduct on the 4th day from ONAM,a festival of kerala. Its the most traditional festival that every keralite used to celebrate. Since i am from thrissur, pulikali is something that i cant avoid during the onam festival.
On the 4th day from the ONAM, the groups of the PULI(TIGER) will come in a procession and circulate the thrissur town. The scene is very eye catching and but its very painful for the people who demonstrate the play. They need to suffer a lot because their body is fully covered with paint. Any how lot of people come to watch the play.See some of the photos i have taken….

Flashback rolls to GOA trip 2003

Posted on Updated on

… it was a day that joy went all its heights… Started from manakala, adoor @ around 6:00 pm…. 60 guys left will all the mood… There was one more partner … WHITE MISCHEIF Who replaced BINNY THOMAS on the trip. We had dinner from Cochin . After we aimed Sri murudeswar, it was just a drop in.. Any way we enjoyed the place with a catching SHIVA Statue.. Next we passed KARWAR and reached GOA in the evening… and beaches  and again..