Friday, July 20, 2012

“Server.Transfer()” vs “Response.Redirect()”

Both “Server.Transfer()” and “Response.Redirect()” are used to transfer a user from one page to another page. Logically both methods are used for the same purpose but still there are some technical differences between both which we need to understand.

The basic difference between them is the way they communicate. Response.Redirect() first sends request for new page to the browser, then browser sends that request to the web-server, and after that your page changes. But Server.Transfer() directly communicate with the server to change the page hence it saves an extra  round-trip (to the browser) in the whole process.

Now the question arises which to use and when to use?

Response.Redirect() should be used when:
  •  we want to redirect the request to some plain HTML pages on our server or to some other web server
  •  we don't care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if it’s necessary)

Server.Transfer() should be used when:
  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don't need to show the real URL where we redirected the request in the users Web Browser

Monday, July 16, 2012

Upload And Remove Files From Table Dynamically

This example shows how to add / remove rows in a grid
simoltaneously. To implement this I have used Repeater Control and DataTable where DataTable is used to store the values entered runtime also remove data if remove command will be passed and Repeater is used to show the data .Final output will be like this one -:

For this add a repeater control on your aspx and  fire properties "onitemcommand " &" onitemdatabound".
 <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand"
        onitemdatabound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table style="border: thin dotted #0000FF; width: 950px">
<tr>
<th>File Category</th>
<th>File Access</th>
<th>File</th>
<th>Description</th>
<th>&nbsp;</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:DropDownList ID="ddlFileCat" runat="server" ></asp:DropDownList>
</td>
<td>
<asp:RadioButtonList ID="rblFileAccsess" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Public</asp:ListItem>
<asp:ListItem>Private</asp:ListItem>
</asp:RadioButtonList>
</td> 
<td>
<asp:Label ID="lblFileNm"  runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FileNm") %>'></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:TextBox ID="txtFileDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FileDesc") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnAddAnother" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Button") %>'  CommandName='<%#DataBinder.Eval(Container.DataItem,"Button") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Repeater's ItemDataBound property is used to bind dropdownlist form database and to show the value as selected runtime.
 protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList ddl = (DropDownList)e.Item.FindControl("ddlFileCat");
            RadioButtonList rbl = (RadioButtonList)e.Item.FindControl("rblFileAccsess");

            SqlDataAdapter adp = new SqlDataAdapter("SELECT [CategoryID],[CatName] FROM [dbo].[MST_FileCategory]", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);

            ddl.DataSource = ds;
            ddl.DataTextField = "CatName";
            ddl.DataValueField = "CategoryID";
            ddl.DataBind();
            ddl.SelectedValue = dtTemp.Rows[i]["FileCat"].ToString();
            rbl.SelectedValue = dtTemp.Rows[i]["FileAccess"].ToString();
            i++;

        }
        //   ddl.SelectedValue = Eval("FileCat").ToString();
    }

To Add or Remove rows from Datatable we will use ItemCommand from where we will pass the Command ADD or REMOVE.

  protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        //int cnt = Repeater1.Items.Count; //get total row count in repeater
        if (e.CommandName == "Add")
        {
            //  cnt++;
            AddColumns();

            foreach (RepeaterItem item in Repeater1.Items)
            {
                //Getting the value of fields
                FileUpload fu = (FileUpload)item.FindControl("FileUpload1");
                Label fileName = (Label)item.FindControl("lblFileNm");
                Button btnAdd = (Button)item.FindControl("btnAddAnother");

                if (btnAdd == e.CommandSource)
                {
                    if (fu.HasFile)
                    {
                        string path = Server.MapPath("~/Docs/");
                        fileName.Text = fu.FileName;
                        fu.SaveAs(path + fileName.Text);
                    }
                }

                string fileCat = ((DropDownList)item.FindControl("ddlFileCat")).SelectedValue;
                string fileAccess = ((RadioButtonList)item.FindControl("rblFileAccsess")).SelectedValue;
                string fileNm = ((Label)item.FindControl("lblFileNm")).Text;
                string fileDesc = ((TextBox)item.FindControl("txtFileDesc")).Text;

                //now chnage button text to remove & save values in table
                dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Remove");
            }
            //Add dummy rows bcoz we neeed to increase
            dtTemp.Rows.Add("", "", "", "", "Add");
            BindWithRepeater();
        }
        else if (e.CommandName == "Remove")
        {
            // cnt--;
            AddColumns();
            foreach (RepeaterItem item in Repeater1.Items)
            {
                Button btnAdd = (Button)item.FindControl("btnAddAnother");
                if (btnAdd != e.CommandSource)
                {
                    string fileCat = ((DropDownList)item.FindControl("ddlFileCat")).SelectedValue;
                    string fileAccess = ((RadioButtonList)item.FindControl("rblFileAccsess")).SelectedValue;
                    string fileNm = ((Label)item.FindControl("lblFileNm")).Text;
                    string fileDesc = ((TextBox)item.FindControl("txtFileDesc")).Text;

                    if (btnAdd.Text == "Remove")
                    {
                        dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Remove");
                    }
                    else
                    {
                        dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Add");
                    }
                }

            }
            BindWithRepeater();
        }

    }

AddColumns() and BindWithRepeater() are user defined functions.Define this functions also and call them in pageload.

  public void AddColumns()
    {
        dtTemp.Columns.Add("FileCat");
        dtTemp.Columns.Add("FileAccess");
        dtTemp.Columns.Add("FileNm");
        dtTemp.Columns.Add("FileDesc");
        dtTemp.Columns.Add("Button");
    }
    public void BindWithRepeater()
    {
        //Bind this Dataset to repeater
        Repeater1.DataSource = dtTemp;
        Repeater1.DataBind();
    }

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            AddColumns();
            dtTemp.Rows.Add("", "", "", "", "Add");
            BindWithRepeater();
        }
    }

Now here is the whole code -: