November 30, 2011

Dynamically Create Link Button and Add Command event

Below is the code which you can write to create Dynmic Link Button in C#


    LinkButton  hl = new LinkButton ();
                        hl.Text = "Delete Check";
                        String D = ds.Tables[0].Rows[i]["Date"].ToString();
                     //   hl.Click += new EventHandler(this.MyButtonHandler);
                        hl.Command += new CommandEventHandler(this.MyButtonHandler);
                        hl.CommandArgument = ds.Tables[0].Rows[i]["ID"].ToString();
                        hl.ID = "DeleteLink" + i.ToString();


                        div3.Controls.Add(hl);
                        div3.Controls.Add(new LiteralControl("<br/>"));


                        ViewState["DataSet"] = ds;




                    }
                    ViewState["recordsCount"] = ds.Tables[0].Rows.Count.ToString();


                }


//Event Handler which executes on Click on the Link Button



 void MyButtonHandler(object sender, CommandEventArgs e)
        {
            string  ID = e.CommandArgument.ToString();
             //Business Logic Comes Here
            }


       }


This Code works perfect when you are creating dynamic Link Buttons On page Load.


But In My case I wanted these links to be created on Some Search Button Click .
and When I was clicking on the Link Button I saw that Event Handler code is not executing because you have to add them on Page_Load when you are dynamically creating them , but here I got the Hack of it .


You recreate the Same Hyperlink in PageLoad also on post back with same "ID"(Link Button ID)
So then I wrote below code on the page load , and it worked well.







protected void Page_Load(object sender, EventArgs e)
    {
               if (IsPostBack)
                {
                    if (ViewState["recordsCount"] != null)
                    {
                        for (int i = 0; i < int.Parse(ViewState["recordsCount"].ToString()); i++)
                        {


                            LinkButton hl = new LinkButton();
                            hl.ID = "DeleteLink" + i.ToString();
                            div3.Controls.Add(hl);
                            hl.Command += new CommandEventHandler(this.MyButtonHandler);
                            DataSet ds1 = (DataSet)ViewState["DataSet"];
                            hl.CommandArgument = ds1.Tables[0].Rows[i]["ID"].ToString();
                               
                        }
                    }
                }




The reason of using ViewState here is my command argument for each link was a cell of a DataSet which I was binding from Data Base . So I saved that DataSet in the view State to make it accessible on PostBack in Page Load

November 18, 2011

Code for Password Hashing in ASP.NET

Below is the simplest method to Hash Passwords in ASP.NET





using System.Web.Configuration;
using System.Web.Security;



protected void btnRegister_Click(object sender, EventArgs e)
    {
        string strUserInputtedHashedPassword =
             FormsAuthentication.HashPasswordForStoringInConfigFile(
                                      txtPwd.Text, "sha1");
        //Write code to insert above password in DB
    }





 protected void btnLogin_Click(object sender, EventArgs e)
    {
        string strUserInputtedHashedPassword =
             FormsAuthentication.HashPasswordForStoringInConfigFile(
                                      txtPwd.Text, "sha1");
        //Write code to Match above password  From DB
    }

November 8, 2011

Set Auto generated columns as read only in Editable Grid View

Below code can be used to make read only columns in grid view


  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        rowIndex = e.NewEditIndex;


        BindData();
        FillGrid();
    }



//Make 1,2,3,4,7,8,9 as readonly

  protected void GridView1_PreRender(object sender, EventArgs e)
    {
        if (rowIndex > -1)
        {
            if (GridView1.Rows.Count > rowIndex)
            {
                if (GridView1.Rows[rowIndex].Cells.Count > 1)
                {
                    if (GridView1.Rows[rowIndex].Cells[1].Controls.Count > 0)
                    {
                        for (int i = 1; i < 4; i++)
                        {
                            if (GridView1.Rows[rowIndex].Cells[i].Controls[0].GetType() == typeof(TextBox))
                            {
                                ((TextBox)GridView1.Rows[rowIndex].Cells[i].Controls[0]).Visible = false;
                                GridView1.Rows[rowIndex].Cells[i].Text
                                    = ((TextBox)GridView1.Rows[rowIndex].Cells[i].Controls[0]).Text;
                            }
                        }
                        for (int j = 7; j < 10; j++)
                        {
                            if (GridView1.Rows[rowIndex].Cells[j].Controls[0].GetType() == typeof(TextBox))
                            {
                                ((TextBox)GridView1.Rows[rowIndex].Cells[j].Controls[0]).Visible = false;
                                GridView1.Rows[rowIndex].Cells[j].Text
                                    = ((TextBox)GridView1.Rows[rowIndex].Cells[j].Controls[0]).Text;
                            }
                        }






                    }
                }
            }
        }
    }

November 4, 2011

Ref Keyword(argument passed by reference) Example in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Ref_Key_Word
{
        class TestRef
        {
            //Pass by Value
            public static void TestWithoutRef(int i)
            {
            i++;
            }


            //Pass by reference
            public static void TestWithRef(ref int i) // note ref
            {
                i++;
            }


            public static void Main()
            {
                //a value will not change after calling a method as is is pass by value
                int a = 2;
                TestWithoutRef(a);
                Console.WriteLine("The value of a is " + a);


                //b value will be chnaged( as it is pass by ref 
                int b = 2;
                TestWithRef(ref b);
                Console.WriteLine("The value of b is " + b);
            }
        }




           
}
Below will be the o/p

November 1, 2011

Open New browser window on Link Button Click

When you want to open a new browser window on link button click.(not the same window)
add below code in your LinkButton

OnClientClick="aspnetForm.target ='_blank';"




see the below code sample


<asp:LinkButton ID="UploadCheckLink" runat="server" OnClientClick="aspnetForm.target ='_blank';" 
                onclick="UploadCheckLink_Click" >Upload Check Images</asp:LinkButton>



 protected void UploadCheckLink_Click(object sender, EventArgs e)
    {        
      Response .Redirect  ("NewWindow.aspx");


    }

Pop Up Window Code in ASP.NET Using JAVA Script

Below is the code to open pop up window is ASP.NET

in .aspx page

 <script type="text/javascript" >
function OpenWindow(url)
{
    newwindow = window.open(url, 'mynewwindow', 'width=500,height=400');  


}
</script>


in .aspx.cs page ( Server Side Code)


protected void OpenNewWindow(object sennder, EventArgs e)
    {
        StringBuilder popupScript = new StringBuilder();
        popupScript.Append("<script language='JavaScript'> window.open('UploadChecks.aspx?OrderSeqNo=" + lblOrderSeqno.Text + "', '', 'width=950, height=580,scrollbars,status,menubar=no,resizable,toolbar=no,titlebar=no,location=no');</script>");
       
    }