How to Implement Loading in Asp.net

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
  <asp:Timer runat="server" ID="timer1" Interval="300000" OnTick="UpdateTimer_Tick">
    </asp:Timer>

//On c# Hand
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
     BtnSearch_OnClick(sender, e);
     lblLastUpdate.Text = System.DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss");
}

<asp:UpdatePanel ID="UP1" runat="server">
    <ContentTemplate>
        --------------------CONTENT HERE----------------------
    </ContentTemplate>
 </asp:UpdatePanel>

 <asp:UpdateProgress AssociatedUpdatePanelID="UP1" ID="updateProgress" runat="server">
        <ProgressTemplate>
            <div id="processMessage" style="position: absolute; top: 45%; left: 45%; padding: 10px;
                width: 22%; z-index: 1001; background-color: yellow; font-family: Arial; font-weight: normal;
                font-size: 10pt; border: thin solid #9CAAC1; height: 65px; text-align: center;">
                Please wait while the document is<br />
                being processed.<br />
            </div>
        </ProgressTemplate>
    </asp:UpdateProgress>

Export Div Content to Image

Design Page Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
   
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>
<script type="text/javascript">
    function ConvertToImage(btnExport) {
        html2canvas($("#dvTable")[0]).then(function (canvas) {
            var base64 = canvas.toDataURL();
            $("[id*=hfImageData]").val(base64);
            __doPostBack(btnExport.name, "");
        });
        return false;
    }
</script>

</head>
<body>
    <form id="form1" runat="server">
   
<div id="dvTable" style = "width:340px;background-color:White;padding:5px">
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
   fggfdgdfgdfgdfg dgdfgfdg dfg df gg<br />
</div>
<br />
<asp:HiddenField ID="hfImageData" runat="server" />
<asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false"
    OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />

    </form>
</body>
</html>
 Program Page Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void ExportToImage(object sender, EventArgs e)
    {
        string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
        byte[] bytes = Convert.FromBase64String(base64);
        Response.Clear();
        Response.ContentType = "image/png";
        Response.AddHeader("Content-Disposition", "attachment; filename=HTML.png");
        Response.Buffer = true;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(bytes);
        Response.End();
    }

}








Detect the browser using ASP.NET and C#

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bool i=supportedBrowser();
        Response.Write(i);
    }

    public bool supportedBrowser()
    {
        string HTTPUserAgent = string.Empty;
        string BrowserName = string.Empty;
        bool isSupportedBrowser;
        HTTPUserAgent = Request.ServerVariables["HTTP_USER_AGENT"];
        BrowserName = BrowserType(HTTPUserAgent);

        if (BrowserName == "Microsoft IE 9" || BrowserName == "Microsoft IE 8" || BrowserName == "Microsoft IE 7" || BrowserName == "Microsoft IE 6")
            isSupportedBrowser = true;
        else
            isSupportedBrowser = false;
        return isSupportedBrowser;
    }

    public string BrowserType(string strHTTPUserAgent)
    {
        string strBrowserUserType = string.Empty; //Holds the users browser type
        //Get the uesrs web browser NOTE: DO NOT CHANGE THE ORDER OF WHAT IS SEARCHED!!
        //Internet Explorer
        if (strHTTPUserAgent.Contains("MSIE 9"))
            strBrowserUserType = "Microsoft IE 9";
        else if (strHTTPUserAgent.Contains("MSIE 8"))
            strBrowserUserType = "Microsoft IE 8";
        else if (strHTTPUserAgent.Contains("MSIE 7"))
            strBrowserUserType = "Microsoft IE 7";
        else if (strHTTPUserAgent.Contains("MSIE 6"))
            strBrowserUserType = "Microsoft IE 6";
        else if (strHTTPUserAgent.Contains("MSIE 5"))
            strBrowserUserType = "Microsoft IE 5";
        else if (strHTTPUserAgent.Contains("MSIE 4"))
            strBrowserUserType = "Microsoft IE 4";
        else if (strHTTPUserAgent.Contains("MSIE 3"))
            strBrowserUserType = "Microsoft IE 3";

        //Firefox
        else if (strHTTPUserAgent.Contains("Firefox/2"))
            strBrowserUserType = "Firefox 2";
        else if (strHTTPUserAgent.Contains("Firefox/1"))
            strBrowserUserType = "Firefox 1";
        else if (strHTTPUserAgent.Contains("Firefox"))
            strBrowserUserType = "Firefox";

        //Netscape and Mozilla
        else if (strHTTPUserAgent.Contains("Netscape/8"))
            strBrowserUserType = "Netscape 8";
        else if (strHTTPUserAgent.Contains("Netscape/7.2"))
            strBrowserUserType = "Netscape 7.2";
        else if (strHTTPUserAgent.Contains("Netscape/7.1"))
            strBrowserUserType = "Netscape 7.1";
        else if (strHTTPUserAgent.Contains("Netscape/7.0"))
            strBrowserUserType = "Netscape 7.0";
        else if (strHTTPUserAgent.Contains("Netscape6"))
            strBrowserUserType = "Netscape 6";
        else if (strHTTPUserAgent.Contains("Mozilla/5"))
            if (strHTTPUserAgent.Contains("rv:1.7"))
                strBrowserUserType = "Mozilla 1.7";
            else
                strBrowserUserType = "Netscape 6";
        else if (strHTTPUserAgent.Contains("Mozilla/4"))
            strBrowserUserType = "Netscape 4";
        else if (strHTTPUserAgent.Contains("Mozilla/3"))
            strBrowserUserType = "Netscape 3";
        else if (strHTTPUserAgent.Contains("Netscape"))
            strBrowserUserType = "Netscape";
        else if (strHTTPUserAgent.Contains("Mozilla"))
            strBrowserUserType = "Mozilla";

        //Opera
        else if (strHTTPUserAgent.Contains("Opera 8"))
            strBrowserUserType = "Opera 8";
        else if (strHTTPUserAgent.Contains("Opera 7"))
            strBrowserUserType = "Opera 7";
        else if (strHTTPUserAgent.Contains("Opera 6"))
            strBrowserUserType = "Opera 6";
        else if (strHTTPUserAgent.Contains("Opera 5"))
            strBrowserUserType = "Opera 5";
        else if (strHTTPUserAgent.Contains("Opera 4"))
            strBrowserUserType = "Opera 4";
        else if (strHTTPUserAgent.Contains("Opera 3"))
            strBrowserUserType = "Opera 3";
        else if (strHTTPUserAgent.Contains("Opera"))
            strBrowserUserType = "Opera";

        //Else unknown or robot
        else
            strBrowserUserType = "Unknown: " + strBrowserUserType;

        return strBrowserUserType;
    }
}


How To Create Multi Level Menu Dynamically Using C# asp.net

 public void GenerateDynamicMenu()
    {
        NavigationMaster menumaster = new NavigationMaster();
        myUtility objutility = new myUtility();
        DataTable dt = new DataTable();
        dt = objutility.GetMenuList();
        Holdinglist = new List<Menu>();
        foreach (DataRow dr in dt.Rows)
        {
            Menu item = new Menu();
            item.menuId = dr["MENU_ID"].ToString();
            item.menuName = dr["MENU_NAME"].ToString();
            item.parentMenuId = dr["MENU_PARENT_ID"].ToString();
            item.url = dr["MENU_URL"].ToString();
            Holdinglist.Add(item);
        }

        TempHoldinglist = new List<Menu>();
        submenuString.Append("<ul id='menu'>");
        string childItems = GetNextNode("0");
        submenuString.ToString().Remove(submenuString.Length - 4, 4);
        submenuString.Append("</ul>");
        showlist.InnerHtml = submenuString.ToString();
    }
    public string GetNextNode(string Parentid)
    {
        int i = 2;
        int j = 2;
        string[] DarktoLightBlueColorList = BlacktoBlueColors.Split(',');
        List<Menu> ListToReturn = new List<Menu>();
        var menuobj = from List in Holdinglist where List.parentMenuId == Parentid select new { List.menuName, List.url, List.menuId };

        foreach (var node in menuobj)
        {
            childCount = Holdinglist.Count(List => List.parentMenuId == node.menuId);
            if (childCount > 0)
            {
               
                    submenuString.Append("<li style='background:" + DarktoLightBlueColorList[j + 1] + "'><a href='" + node.url + "'>" + node.menuName + "</a><span style='float:right;padding-right:7px;margin-top:-18px'><img width='12px' height='14px' src='" + imageurl + "' /></span><ul>");
            
                j++;
                GetNextNode(node.menuId);
            }
            else
            {
                i = j - 1;
                submenuString.Append("<li style='background:" + DarktoLightBlueColorList[i + 2] + "'><a href='" + Page.ResolveClientUrl("~/" + node.url) + "'>" + node.menuName + "</a></li>");
                i++;
                j++;
            }

            if (i == 15)
            {
                i--;
            }
        }
        submenuString.Append("</ul></li>");
        return submenuString.ToString();
    }

How to check Inputs Fields blank or not in Gridview

protected void btnSubmit_Click(object sender, EventArgs e)
{
        foreach (GridViewRow gvr in gridEvalution.Rows)
        {
            RadioButtonList rbl = (RadioButtonList)gvr.FindControl("rbtnList");
            if (rbl.SelectedIndex == -1)
            {
                ScriptManager.RegisterStartupScript(this,this.GetType(),"Alert()","alert('Please Select All Question.');",true);
                return;
            }
        }
}

Image Button click event in gridview

protected void imgMEvlt_Click(object sender, EventArgs e)
     {
        ImageButton lbtnedit = (ImageButton)sender;
        GridViewRow row = (GridViewRow)lbtnedit.NamingContainer;
        HiddenField PROCESSTRANSID = (HiddenField)row.FindControl("hd_transprocid");
        string PROCTRANSID = PROCESSTRANSID.Value.ToString();
        String script = "fnOpen('UpdateRuningProcess.aspx?PROCID=" + PROCTRANSID+"')";
        ScriptManager.RegisterClientScriptBlock(Page, GetType(), new Guid().ToString(), script, true);
     }

How to access c# function in gridview

  protected String GetEncryptedString(String strNormalString)
    {
        return Server.UrlEncode(Encryption.Encrypt(strNormalString));
    }
  <asp:TemplateField>
   <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="8%" />
   <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="8%" />
    <ItemTemplate>
     <a href="MyRequestDetail.aspx?ServiceRequestId=<%# GetEncryptedString(Eval("RequestId").ToString()) %>"><img src="../../../images/81_edit.png" /></a>
    </ItemTemplate>
   </asp:TemplateField>

How to Generate Dynamic folder on runtime in asp.net

 DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("UploadedFiles"));
 if (!thisFolder.Exists)
 {
      thisFolder.Create();
 }

How to Add dynamic textbox on every button click and textbox values

Design Page:
<asp:HiddenField ID="hdnCount" Value="1" runat="server" />
<asp:Table ID="tblMain" runat="server">
    <asp:TableHeaderRow>
        <asp:TableHeaderCell>
            <asp:Button ID="btnAdd" runat="server"
                Text="Add"
                OnClick="btnAdd_Click"/>
            <asp:Button ID="btnSave" runat="server"
                Text="Save"
                OnClick="btnSave_Click" />
        </asp:TableHeaderCell>
    </asp:TableHeaderRow>
    <asp:TableRow>
        <asp:TableCell>
            <asp:TextBox ID="txtName1" runat="server"
                Width="200">
               
            </asp:TextBox>
        </asp:TableCell>
    </asp:TableRow>
</asp:Table>

Code Page:-
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Linq;
using System.Drawing;

public partial class Default10 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateTextBoxes();
    }

    private void CreateTextBoxes()
    {
        int count = int.Parse(hdnCount.Value);

        // Recreate the textboxes on each postback
        for (int i = 2; i <= count; i++)
        {
            TextBox tb = new TextBox();
            tb.ID = "txtName" + i.ToString();
            tb.Width = 200;
            tb.Text = Request.Form["txtName" + i.ToString()];

            TableRow tr = new TableRow();
            TableCell tc = new TableCell();


            tc.Controls.Add(tb);
            tr.Cells.Add(tc);
            tblMain.Rows.Add(tr);
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
{
    int count = int.Parse(hdnCount.Value);
    count++;
    hdnCount.Value = count.ToString();

    TextBox tb = new TextBox();
    tb.ID = "txtName" + count.ToString();
    tb.Width = 200;

    TableRow tr = new TableRow();
    TableCell tc = new TableCell();

    tc.Controls.Add(tb);
    tr.Cells.Add(tc);
    tblMain.Rows.Add(tr); 
}

protected void btnSave_Click(object sender, EventArgs e)
{
   
    int rowCount = int.Parse(hdnCount.Value);

    for (int rowNumber=1; rowNumber<=rowCount; rowNumber++ )
    {
        TextBox tb = (TextBox)tblMain.Rows[rowNumber].Cells[0].FindControl
        ("txtName" + rowNumber.ToString());
        if (tb != null)
            Response.Write(tb.Text + "<br/>");
    }
}
}

How to Update Parent Window after close child window

Parent Page Code:-
<a href="javascript:openDialog('IRClearanceActivation.aspx?empcode=<%# Eval("ADEMPCODE") %>&ResigID=<%# Eval("RESIGNATIONID") %>',800,480)">
<img id="Img2" style="padding-right: 2px; vertical-align: middle" src="../../Images/icon_ticketbullet.gif" runat="server" alt="Ticket" />
<b>ACTIVATE</b></a>
    <script type="text/javascript">
    function openPopupwithScrol(strOpenUrl, width, height) {
            var winTop = (screen.height - height) / 2;
            var winLeft = (screen.width - width) / 2;
            var windowFeatures = "location=no,status=no,width=" + width + ",height=" + height;
            windowFeatures = windowFeatures + ",left = " + winLeft + ",";
            windowFeatures = windowFeatures + "top=" + winTop + ",resizable" + ",scrollbars";
            //window.open (strOpenUrl, "mywindow", "TOOLBAR=no,MENUBAR=no,SCROLLBARS=yes,RESIZABLE=no,LOCATION=no,DIRECTORIES=no,STATUS=no,width="+width+",height="+height);
            window.open(strOpenUrl, "mywindow", windowFeatures);
        }
        function openDialog(strOpenUrl, width, height) {
             var retVal = window.showModalDialog(strOpenUrl, null, "dialogHeight:" + height + "px;dialogWidth:" + width + "px;status:0;resizable:1;edge:raised;scroll:1");
            if (retVal == "1") {
                window.location = "ListPendingClearance.aspx";
                }
        }
    </script>

Child Window Code:-
 BTN Click:- ScriptManager.RegisterClientScriptBlock(Page, GetType(), "al1", "alertMe('1')", true);
 <script language="javascript" type="text/javascript">
   function alertMe(val)
   {   
        if(val=="1")
        {
            alert("Information updated successfully");
            window.returnValue ="1";
            window.close();
        }
        else if(val=="2")
        {
            alert("Update failed");
            window.returnValue ="1";
            window.close();
        }
   }
   </script>

Serial No in Data control in asp.net

<asp:Label ID="Label9" runat="server" Text='<%# Container.DataItemIndex + 1 %>'></asp:Label>

Accessing nested master page control in child page

try
            {

            }
            catch (Exception ex)
            {
                ((Label)((ContentPlaceHolder)this.Master.Master.FindControl("ContentPlaceHolder1")).FindControl("lblError")).Text = ex.Message;
            }

Default size and file size limit in asp:FileUpload control

Using the asp:FileUpLoad to upload files works fine except the file size does not exceed the maximum allowed. When the maximum is exceeded. I get an error "Internet Explorer cannot display the webpage". The problem is the try catch block doesn't catch the error so I cannot give the user a friendly message that they have exceed the allowable size. I have seen this problem while searching the web but I cannot find an acceptable solution.

Default file size limit is (4MB) but you can change the default limit in a localized way by dropping a web.config in the directory where your upload page lives. That way you don't have to make your whole site allow huge uploads (doing so would open you up to a certain kinds of attacks).
Just set in web.config under <system.web> section. e.g. In the below example I am setting the maximum length that is 2GB
<httpRuntime maxRequestLength="2097152" executionTimeout="600" />
Please note that the maxRequestLength is set in KB's and it can be set up to 2GB (2079152 KB's). Practically we don't often need to set 2GB request length, but if you set the request length higher, we also need to increase the executionTimeout.
Execution Timeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.) 
For Details please read httpRuntime Element (ASP.NET Settings Schema)

Now if you want to show the custom message to user, if the file size is greater than 100MB.
You can do like..
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 104857600)
{
    //FileUpload1.PostedFile.ContentLength -- Return the size in bytes
    lblMsg.Text = "You can only upload file up to 100 MB.";
}

Validation Controls in ASP.Net

  1. RequiredFiledValidator
  2. RangeValidator
  3. CompareValidator
  4. RegularExpressionValidator
  5. CustomValidator
  6. Validation Summary
1. RequiredFiledValidator: Makes an input control a required field. Example
    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmailId" runat="server" ControlToValidate="txtEmailId"
        ErrorMessage="Email Id is Required" ValidationGroup="Submit"></asp:RequiredFieldValidator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
2. RangeValidator: Checks that the user enters a value that falls between two values. Example
    <asp:TextBox ID="txtWorkingDays" runat="server"></asp:TextBox>
    <asp:RangeValidator ID="RangeValidatorWorkingDays" runat="server" ControlToValidate="txtWorkingDays"
        MaximumValue="7" MinimumValue="1" ErrorMessage="Working day must be between 1 to 7"
        ValidationGroup="Submit"></asp:RangeValidator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
  
3. CompareValidator: Compares the value of one input control to the value of another input control or to a fixed value. Example
    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
    <asp:TextBox ID="txtEmailIdReEnter" runat="server"></asp:TextBox>
    <asp:CompareValidator ID="CompareValidatorEmailId" runat="server" ControlToCompare="txtEmailId"
        ControlToValidate="txtEmailIdReEnter" ErrorMessage="Email Id and Re Enter Email Id must be same"
        ValidationGroup="Submit"></asp:CompareValidator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
4. RegularExpressionValidator: The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern. Example
    <asp:TextBox ID="txtPinCode" runat="server"></asp:TextBox>
    <asp:RegularExpressionValidator ID="RegularExpressionValidatorPindCode" runat="server"
        ControlToValidate="txtPinCode" ValidationExpression="\d{6}" ErrorMessage="The pin code must be 6 numeric digits!"
        ValidationGroup="Submit" />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
5. CustomValidator: The CustomValidator control allows you to write a method to handle the validation of the value entered. Example
Client Side Validation:
<asp:TextBox ID="txtPinCode" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidatorPinCode" runat="server" ControlToValidate="txtPinCode"
        ClientValidationFunction="validate" ErrorMessage="Name  must be more than 2"
        ValidationGroup="Submit"></asp:CustomValidator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
<script type="text/javascript">
    function validate(sender, e) {
        var ctrl = document.getElementById('<%= txtPinCode.ClientID %>');
        e.IsValid = false;
        if (ctrl.value.length == 6) {
            e.IsValid = true;
        }
    }
</script>
Server Side Validation:

<asp:TextBox ID="txtPinCode" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidatorPinCode" runat="server" ControlToValidate="txtPinCode"
        OnServerValidate="validate" ErrorMessage="No of characters must be between 5 and 8"
        ValidationGroup="Submit"></asp:CustomValidator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
    protected void validate(object sender, ServerValidateEventArgs e)
    {
        if (e.Value.Length == 6)
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }

6. Validation Summary: The ValidationSummary control is used to display a summary of all validation errors occurred in a Web page. Example

    <asp:TextBox ID="txtPinCode" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtPinCode"
        ErrorMessage="Email Id is mandatory" Text="*" ValidationGroup="Submit"></asp:RequiredFieldValidator>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableClientScript="true" ValidationGroup="Submit" />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />

How to Create Chart in asp.net c#

 Design page code:-
<asp:Chart EnableViewState="false" ID="Chart1"  runat="server"  ImageStorageMode="UseHttpHandler" Width="560" Height="400">
 <Titles>
      <asp:Title ShadowColor="32, 0, 0, 0"  TextStyle="Shadow" Font="Trebuchet MS, 14.25pt, style=Bold"     ForeColor="26, 59, 105">
     </asp:Title>
  </Titles>
  <Legends>
        <asp:Legend LegendStyle="Row" IsTextAutoFit="False" DockedToChartArea="ChartArea1"
         Docking="Top" IsDockedInsideChartArea="False" Name="Default" BackColor="Transparent"
         Font="Trebuchet MS, 8.25pt, style=Bold" Alignment="Far"></asp:Legend>
  </Legends>
  <Series>
     <asp:Series ChartArea="ChartArea1" IsValueShownAsLabel="true" ChartType="Column"
     LegendText="Average Score" Name="Series1" LabelForeColor="#150517" BorderColor="180, 26, 59, 105"
     CustomProperties="EmptyPointValue=Zero" Color="220, 65, 140, 240" IsXValueIndexed="True"
     Label="#VALY" LabelToolTip="#VALX">
     <EmptyPointStyle MarkerStyle="Diamond" MarkerColor="224, 64, 10"></EmptyPointStyle>
    </asp:Series>
  </Series>
  <ChartAreas>
       <asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BackSecondaryColor="Transparent"
        BackColor="64, 165, 191, 228" ShadowColor="Transparent" BackGradientStyle="TopBottom">
         <AxisY LineColor="64, 64, 64, 64">
             <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
             <MajorGrid LineColor="64, 64, 64, 64" />
         </AxisY>
          <AxisX LineColor="64, 64, 64, 64">
                <LabelStyle Font="Trebuchet MS, 8.25pt" />
                <MajorGrid LineColor="64, 64, 64, 64" />
           </AxisX>
    </asp:ChartArea>
  </ChartAreas>

</asp:Chart>

C# Page Code:-
 DataTable dt = objReport.OVERALLTNGEffEvalAvgScore(TRAININGNAME, STRKI, stroperation);
  if (dt.Rows.Count > 0)
    {
       Chart1.DataSource = dt;
         string titletxt="Average score of " + dp_traininglist.SelectedItem.Text;
         Chart1.Titles.Add(new Title(titletxt, Docking.Top, new Font("Trebuchet MS", 14f, FontStyle.Bold),       Color.Black));
         Chart1.Series["Series1"].XValueMember = "OPERATION";
         Chart1.Series["Series1"].YValueMembers = "AVGSCORE";
         Chart1.Series["Series1"]["PointWidth"] = "0.3";

        Chart1.DataBind();
        Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
        Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = true;
         Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
     }

Datatable Select and Sort

I have used to select method to get the data from datatable.
For example



DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Group", typeof(int)));
        dt.Columns.Add(new DataColumn("name", typeof(string)));
        DataRow dr = dt.NewRow();
        dr["Group"] = 1;
        dr["name"] = "Apple";
        dt.Rows.Add(dr);
        dr["Group"] = 2;
        dr["name"] = "Milk";
        dt.Rows.Add(dr);
        dr["Group"] = 1;
        dr["name"] = "Orange";
        dt.Rows.Add(dr);
        dr["Group"] = 2;
        dr["name"] = "Curd";
        dt.Rows.Add(dr);
So the following order the data is in datatable

Group    Name
=================
1       Apple
2       Milk
1       Orange
2       Curd

The following select statement to get the data.
DataRow[] dr1 = dt.Select("group in (1,2)"); 
But the items are fetching different order. like this

Group    Name
====================
1       Apple
1       Orange
2       Milk
2       Curd
I need to fetching the actual order.  Like this

Group    Name
====================
1       Apple
2       Milk
1       Orange
2       Curd
I tried to use dataview rowfilter instead of datatable.select when it is working fine. 
Here this, 
DataView dv = dt.DefaultView;
dv.RowFilter = "group in (1,2)";
dt = dv.ToTable(); 

To get output in multiple line from a TextBox with TextMode property as Multiline in asp.net using C#

string MailBody = txtMailBody.Text.Replace(Environment.NewLine, "<br />");

Visible Button with condition of Backend Value in Gridview or Repeater

<asp:Button ID="lnk_ship" runat="server" CssClass="btn-mini" Text="Ship Software" Visible='<%# DataBinder.Eval(Container.DataItem, "shipped" ).ToString() == "Yes" ? true : false %>' />

How to check Strong Password

public static bool IsPasswordStrong(string password)
{
  // Check for strong password
  return Regex.IsMatch(password, @"^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$");
}


protected void cmdSubmit_Click(object sender, EventArgs e)
{
        string strtxtNewPwd = txtNewPwd.Text;
        if (IsPasswordStrong(strtxtNewPwd) == false)
        {
            errorpanel.Style.Add(HtmlTextWriterStyle.Display, "inline");
            status.Text = "Password must be atleast 8 characters long and should be a mix of atleast One Uppercase letter, One Lowercase letter and One Numeral.";
        }
        else
        {
            // Update password
        }
}



Guidelines for creating strong password 
Be at least eight characters long. Because of the way passwords are encrypted, the most secure passwords are 8 or 14 characters long.
Contain at least one character from the following three groups:

Group  Examples 
Uppercase Letters  A,B,C... 
Lowercase Letters  a,b,c... 
Numerals  0,1,2,3,4,5,6,7,8,9 

Be significantly different from prior passwords.
Not contain your name or user name.
Not be a common word or name.
Exapmle:- Password1  => (P)Uppercase, (assword)Lowercase, (1)Numeral

Encrypt and Decrypt the Password

 private string Encryptdata(string password)
    {
        string strmsg = string.Empty;
        byte[] encode = new byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        strmsg = Convert.ToBase64String(encode);
        return strmsg;
    }

    private string Decryptdata(string encryptpwd)
    {
        string decryptpwd = string.Empty;
        UTF8Encoding encodepwd = new UTF8Encoding();
        Decoder Decode = encodepwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
        int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        decryptpwd = new String(decoded_char);
        return decryptpwd;
    }

How to check the Length of the File in c#

txtEFileUpload.PostedFile.ContentLength <= 2048000

If Condition in Design Page

<% if(Request.QueryString["id"]==null){ %>
                         <tr class="row1">
                                            <td align="left" style="width: 125px">
                                                <strong>
                                                &nbsp;Upload File</strong></td>
                                            <td align="left" colspan="2" style="width: 672px">
                                                &nbsp;<asp:FileUpload ID="txtFileUpload" runat="server" CssClass="swifttext" />
                                                </td>
                                        </tr>
                                        <%} else{%>
                                        <tr class="row1">
                                            <td align="left" style="width: 125px">
                                                <strong>
                                                &nbsp;Upload File</strong></td>
                                            <td align="left" colspan="2" style="width: 672px">
                                                <table cellpadding="0" cellspacing="0" border="0">
                                                    <tr>
                                                        <td><asp:HyperLink ID="FileList" runat="server" Target="_blank"><img src="../../Images/menu_pdf.gif" /></asp:HyperLink>
                                                        </td>
                                                        <td>
                                                            &nbsp;<asp:HyperLink ID="RemoveImg" runat="server"><img src="../../Images/del.gif" /></asp:HyperLink>
                                                            &nbsp;<asp:FileUpload ID="txtEFileUpload" Visible="false" runat="server" CssClass="swifttext" />
                                                        </td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                        <%} %>              

Message Alert

 ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Remarks is Required Field');", true);
 Response.Write("<script LANGUAGE='JavaScript' >alert('Account Success Inserted');document.location='" + ResolveClientUrl("Account.aspx") + "';</script>");

 Note:-If your Srcript manager message not show you write (return;) after script manager

Drop down List Item Value select in Gridview from backend

<asp:DropDownList Enabled="false" ID="statusdropdown" SelectedValue='<%# Eval("status") %>' runat="server">
<asp:ListItem Value="1">Active</asp:ListItem>
<asp:ListItem Value="0">Deactive</asp:ListItem>
</asp:DropDownList>