Menu ▼


<< < 1 2 3 4 > >>

By default asp.net updatepanel will not maintain the div/panel scroll position after partial post back. To main the scroll position we need to add our own javascript.

Note: You need to add the below javascript code after the scriptmanager tag.

<script type="text/javascript">
    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    function BeginRequestHandler(sender, args) {
        if ($get('divid') != null) {
            xPos = $get('divid').scrollLeft;
            yPos = $get('divid').scrollTop;
        }
    }

    function EndRequestHandler(sender, args) {
        if ($get('divid') != null) {
            $get('divid').scrollLeft = xPos;
            $get('divid').scrollTop = yPos;
        }
    }

    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
</script>
Read More...
Submited By : mrkraju On 08 Feb 2017

This example shows you how to bind data to DropDownList in GridView based on the Grid Row Value. In this example we will bind the States to DropDownList based on Country in Row.

In the GridView RowDataBound we will find the DropDownList and Country then fetch the state list for the Country and bind the state list to DropDownList.

RowDataBound event

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int CountryID = int.Parse(((HiddenField)e.Row.FindControl("hidCountryID")).Value);
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlState");
            ddl.DataSource = GetStates(CountryID);
            ddl.DataTextField = "State";
            ddl.DataValueField = "StateID";
            ddl.DataBind();
        }
    }

Example
Dropdown binding in GridView

CS Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Text;
using System.Collections;

namespace WebApp
{
    public partial class Sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillGrid();
            }
        }

        void FillGrid()
        {
            gv.DataSource = GetCountries();
            gv.DataBind();
        }

        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int CountryID = int.Parse(((HiddenField)e.Row.FindControl("hidCountryID")).Value);
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlState");
                ddl.DataSource = GetStates(CountryID);
                ddl.DataTextField = "State";
                ddl.DataValueField = "StateID";
                ddl.DataBind();
            }
        }

        DataTable GetCountries()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CountryID", typeof(int));
            dt.Columns.Add("Country", typeof(string));
            dt.Rows.Add(1, "Australia");
            dt.Rows.Add(2, "New Zealand");
            dt.Rows.Add(3, "India");
            dt.Rows.Add(4, "USA");
            return dt;
        }

        DataTable dtStates = null;

        DataTable GetStates(int CountryID)
        {
            if (dtStates == null)
            {
                dtStates = new DataTable();
                dtStates.Columns.Add("CountryID", typeof(int));
                dtStates.Columns.Add("StateID", typeof(string));
                dtStates.Columns.Add("State", typeof(string));
                dtStates.Rows.Add(1, 1, "Albury");
                dtStates.Rows.Add(1, 2, "Dubbo");
                dtStates.Rows.Add(1, 3, "Sydney");
                dtStates.Rows.Add(2, 1, "Auckland");
                dtStates.Rows.Add(2, 2, "Hamilton");
                dtStates.Rows.Add(2, 3, "Wellington");
                dtStates.Rows.Add(3, 1, "Delhi");
                dtStates.Rows.Add(3, 2, "Hyderabad");
                dtStates.Rows.Add(3, 3, "Mumbai");
                dtStates.Rows.Add(4, 1, "Chicago");
                dtStates.Rows.Add(4, 2, "New York");
                dtStates.Rows.Add(4, 3, "Washington DC");
            }
            dtStates.DefaultView.RowFilter ="CountryID=" + CountryID;
            return dtStates.DefaultView.ToTable();
        }


    }

}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="WebApp.Sample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" 
            CellPadding="5" CellSpacing="5" ForeColor="#333333" GridLines="Both" 
            onrowdatabound="gv_RowDataBound"  >
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:HiddenField ID="hidCountryID" runat="server" Value='<%#Eval("CountryID") %>' />
                        <asp:Label ID="lblCountry" runat="server" Text='<%#Eval("Country") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="State">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlState" runat="server" style="width:100%">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 20 Jun 2016

Asp.net requiredfieldvalidator is used to make an input control as required field(mandatory). If you want to associate the requiredfieldvalidator to a textbox then you have to give the textbox id to requiredfieldvalidator ControlToValidate property.

Syntax

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Name Required" ForeColor="Red" ControlToValidate="txtName"></asp:RequiredFieldValidator>

Example

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Name:<br />
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Name Required"
            ForeColor="Red" ControlToValidate="txtName"></asp:RequiredFieldValidator>
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-size: 18px; font-weight: bold;"></asp:Label>
    </div>
    </form>
</body>
</html>

ASPX Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Globalization;

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

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "Submitted successfully.";
    }
}

Read More...
Submited By : mrkraju On 01 Dec 2015

Asp.net radio button is used to allow user to select any one of option among multiple. For example allowing user to select gender either male or female. And you can call server side c# code (postback) when the user select the radio button. To do that you have to specify the AutoPostBack="true" and implement the OnCheckedChanged="rbtn_CheckedChanged". Below example will let you know how to implement it.

Allowing user to select single option
To allow user to select single option from multiple you need to set the GroupName. For example if you want to allow user to select gender either male or female then you have to set GroupName="gender" for both the radio buttons (Radio buttons which are not set the GroupName property can be selected multiple).

<asp:RadioButton ID="rbtnMale" runat="server" GroupName="gender" Text="Male" />

<asp:RadioButton ID="rtbnFemale" runat="server" GroupName="gender" Text="Female" />

Reading asp.net radio button value (selected or not) in c#
RadioButton.Checked property will return true value when the radio button is selected, other wise it will return false.

if(rbtnIndia.Checked)
{

}

Calling server side code (radio button postback event) in asp.net

protected void rbtn_CheckedChanged(object sender, EventArgs e)
{
    DataTable dt = GetData();
    if (rbtnIndia.Checked)
        dt.DefaultView.RowFilter="CountryID=1";            
    else            
        dt.DefaultView.RowFilter = "CountryID=2";            

    ddlStates.DataSource = dt.DefaultView.ToTable();
    ddlStates.DataTextField = "StateName";
    ddlStates.DataValueField = "StateID";
    ddlStates.DataBind();
}

Example
asp.net radio button example.

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:RadioButton ID="rbtnMale" runat="server" GroupName="gender" Text="Male" />
        <br />
        <asp:RadioButton ID="rtbnFemale" runat="server" GroupName="gender" Text="Female" />
        <br />
        <br />
        <br />
        <asp:RadioButton ID="rbtnIndia" runat="server" GroupName="country" Text="India" AutoPostBack="true"
            OnCheckedChanged="rbtn_CheckedChanged" />
        <br />
        <asp:RadioButton ID="rbtnUSA" runat="server" GroupName="country" Text="USA" AutoPostBack="true"
            OnCheckedChanged="rbtn_CheckedChanged" />
        <br />
        <br />
        States:<br />
        <asp:DropDownList ID="ddlStates" runat="server">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

C# Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Globalization;

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


        }

        DataTable GetData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CountryID", typeof(int));
            dt.Columns.Add("CountryName", typeof(string));
            dt.Columns.Add("StateID", typeof(int));
            dt.Columns.Add("StateName", typeof(string));
            dt.Rows.Add(1, "India", 1, "Andhra Pradesh");
            dt.Rows.Add(1, "India", 2, "Karnataka");
            dt.Rows.Add(1, "India", 3, "Maharashtra");
            dt.Rows.Add(2, "USA", 4, "California");
            dt.Rows.Add(2, "USA", 5, "New Jersey");
            dt.Rows.Add(2, "USA", 6, "Texas");
            return dt;
        }

        protected void rbtn_CheckedChanged(object sender, EventArgs e)
        {
            DataTable dt = GetData();
            if (rbtnIndia.Checked)
                dt.DefaultView.RowFilter = "CountryID=1";
            else
                dt.DefaultView.RowFilter = "CountryID=2";

            ddlStates.DataSource = dt.DefaultView.ToTable();
            ddlStates.DataTextField = "StateName";
            ddlStates.DataValueField = "StateID";
            ddlStates.DataBind();
        }

    }

}

Read More...
Submited By : mrkraju On 30 Nov 2015

Asp.net checkbox is used to allow user to select multiple options. For example you are offering training for multiple technologies then you can use checkbox to allow select multiple courses. And you can call server side c# code (postback) when the user select or unselect a checkbox. To do that you have to sepecify the AutoPostBack="true" and implement the OnCheckedChanged="chbTutorial_CheckedChanged". Below example will let you know how to implement it.

Reading asp.net checkbox value (selected or not) in c#
Checkobox.Checked property will return true value when the checkbox is checked, other wise it will return false.

chbTutorial.Checked

Calling server side code (checkbox postback event) in asp.net

<asp:CheckBox ID="chbTutorial" runat="server" Text="Opt for online tutorial" AutoPostBack="true"
    OnCheckedChanged="chbTutorial_CheckedChanged" />
<br /><br />
<asp:Label ID="lblMessage" runat="server" Style="color: Green; font-size: 18px; font-weight: bold;"></asp:Label>

protected void chbTutorial_CheckedChanged(object sender, EventArgs e)
{
    if (chbTutorial.Checked == true)
        lblMessage.Text = "You have opeted for online tutorial.";
    else
        lblMessage.Text = "";
}

Example
asp.net checkbox example

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        You can select multiple courses:<br />
        <asp:CheckBox ID="chbAspnet" runat="server" Text="Asp.net" /><br />
        <asp:CheckBox ID="chbCSharp" runat="server" Text="CSharp" /><br />
        <br />
        <br />
        Checkbox postback event:<br />
        <asp:CheckBox ID="chbTutorial" runat="server" Text="Opt for online tutorial" AutoPostBack="true"
            OnCheckedChanged="chbTutorial_CheckedChanged" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-size: 18px; font-weight: bold;"></asp:Label>
    </div>
    </form>
</body>
</html>

CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Globalization;

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

    }

    protected void chbTutorial_CheckedChanged(object sender, EventArgs e)
    {
        if (chbTutorial.Checked == true)
            lblMessage.Text = "You have opeted for online tutorial.";
        else
            lblMessage.Text = "";
    }
}

Read More...
Submited By : mrkraju On 29 Nov 2015

This example will show you how to get client/end user ip address, operating system, browser name and browser version in asp.net and c#.

CS Code
Below c# code will get the client ip address, operating system, browser name and version details in asp.net page load event using c#.

protected void Page_Load(object sender, EventArgs e)
{
    HttpBrowserCapabilities browserCapabilities = Request.Browser;

    //getting client ip address
    string ipAddress = HttpContext.Current.Request.UserHostAddress;

    //getting client browser name
    string browserName = browserCapabilities.Browser;

    //getting client browser version
    string browserVersion = browserCapabilities.Version;

    //getting client operating system
    string operatingSystem = getOperatinSystemDetails(Request.UserAgent);
}

public static string getOperatinSystemDetails(string browserDetails)
{
    try
    {
        switch (browserDetails.Substring(browserDetails.LastIndexOf("Windows NT") + 11, 3).Trim())
        {
            case "6.2":
                return "Windows 8";
            case "6.1":
                return "Windows 7";
            case "6.0":
                return "Windows Vista";
            case "5.2":
                return "Windows XP 64-Bit Edition";
            case "5.1":
                return "Windows XP";
            case "5.0":
                return "Windows 2000";
            default:
                return browserDetails.Substring(browserDetails.LastIndexOf("Windows NT"), 14);
        }
    }
    catch
    {
        if (browserDetails.Length > 149)
            return browserDetails.Substring(0, 149);
        else
            return browserDetails;
    }
}

Read More...
Submited By : mrkraju On 23 Nov 2015

Radio buttons are used to allow user to select a single option among multiple. But if we use radio button in gridview rows, user can select multiple rows (radio buttons) even though you mention radio button group for the radio buttons it will not restrict the user to select only one row. To restrict user to select only one row(radio button) we can write a javascript function (jquery) on radio button click event below example will let you know how to do that.

Example

SelectPlanPrice
Silver100
Gold200
Dimond300

Javascript/jQuery function

<script language="javascript">
    function singleRbtnSelect(chb) {
        $(chb).closest("table").find("input:radio").prop("checked", false);
        $(chb).prop("checked", true);
    }
</script>

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script language="javascript">
        function singleRbtnSelect(chb) {
            $(chb).closest("table").find("input:radio").prop("checked", false);
            $(chb).prop("checked", true);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvPlans" runat="server" AutoGenerateColumns="False" BackColor="White"
            BorderColor="#3366CC" BorderWidth="1px" CellPadding="4">
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <RowStyle BackColor="White" ForeColor="#003399" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <SortedAscendingCellStyle BackColor="#EDF6F6" />
            <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
            <SortedDescendingCellStyle BackColor="#D6DFDF" />
            <SortedDescendingHeaderStyle BackColor="#002876" />
            <Columns>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:RadioButton ID="rbtnPlan" runat="server" onclick="singleRbtnSelect(this);" />
                        <asp:HiddenField ID="hidPlanID" runat="server" Value='<%#Eval("PlanID")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Plan" DataField="Plan" ItemStyle-Width="200">
                    <ItemStyle Width="200px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField HeaderText="Price" DataField="Price" ItemStyle-Width="200">
                    <ItemStyle Width="200px"></ItemStyle>
                </asp:BoundField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

CS page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PlanID", typeof(int));
        dt.Columns.Add("Plan", typeof(string));
        dt.Columns.Add("Price", typeof(decimal));
        dt.Rows.Add(1, "Silver", 100);
        dt.Rows.Add(2, "Gold", 200);
        dt.Rows.Add(3, "Dimond", 300);
        gvPlans.DataSource = dt;
        gvPlans.DataBind();
    }
    
}

Read More...
Submited By : mrkraju On 22 Nov 2015

Session state and application variable are part of Asp.net server side state management concepts. If you want to save the user specific data use session state. If you want to save the application level data then use application variable.


Session

  • Sesions are is used to save the user specific data like UserID, User Role, etc. And can be accessible only by that user.
  • Data stored in the SesionState will be cleared when the session expired(usually after 20min of inactivity when using session inproc).


Application variable

  • Application variable are used to save the application level data. And can be accessible by all the users.
  • Data stored in the Application variable will be cleared when the application restart.

Read More...
Submited By : mrkraju On 20 Nov 2015

When your website is under maintenance then you can place the app_offline.htm page in the root folder so that any user access the website(any page) they will get the app_offline.htm page.
When you have custom redirects for httpErrors in your website, you may get the message "The service is unavailable" message when you place the app_offline.htm page in your website. To resolve this issue just add the below configuration in your web.config file under httpErrors section.

Example

<httpErrors errorMode="Custom" existingResponse="Replace">
  <error statusCode="503" path="App_Offline.htm" responseMode="File" />
</httpErrors>

Read More...
Submited By : mrkraju On 18 Nov 2015

When we open a website a default page will be opened. You can set which page should be opened or which is the default page in the website in web.config file. You can set the default document in defaultDocument section under system.webServer section in web.config file. Below example will let you know how to set the default document in asp.net web.config file.

Example

<system.webServer>
<defaultDocument>
  <files>
    <add value="Home.aspx"/>
  </files>
</defaultDocument>
</system.webServer>

Read More...
Submited By : mrkraju On 17 Nov 2015
<< < 1 2 3 4 > >>




Search dotnetlearners.com