Menu ▼


<< < 1 2 3 4 5 6 7 8 9 > >>

To take backup of dll in GAC follow the below setps.

  • Open Windows Run
  • Type C:\Windows\assembly\GAC_MSIL and click enter
  • All the GAC MSIL dll's will be opened
  • You can take backup of what ever dll you want

Read More...
Submited By : mrkraju On 14 Jul 2016

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

This example shows you how to write C# extension method and how to convert DataSet to JSON using JavaScriptSerializer.

By default DataSet doesnot have GetJSON method to get JOSN string from DataSet. So in this example I have written an extension method to add GetJSON method to DataSet and it will return JSON String as output.

    public static class DataSetExt
    {
        public static string GetJSON(this DataSet ds)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ArrayList root = new ArrayList();
            List<Dictionary<string, object>> table;
            Dictionary<string, object> data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }
            
            return serializer.Serialize(root);
        }
    }

Steps to write GetJSON extension method.

  • Class should be declared as static
  • Method name should be declared as static
  • Method parameter should be starts with "this" keyword and the Object(DataSet) and variable name(ds).
  • Using System.Web.Script.Serialization.JavaScriptSerializer we converted the DataSet to JSON using Dictionary and ArrayList.

Example
C# extension method

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)
        {
            
        }

        protected void btnGetJSON_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("Employee Name", typeof(string));
            dt.Columns.Add("Salary", typeof(decimal));
            dt.Columns.Add("Department", typeof(string));
            dt.Rows.Add("John", 5000.00, "Marketing");
            dt.Rows.Add("Smith", 4000.00, "IT");
            dt.Rows.Add("Williams", 6000.00, "Sales");
            dt.Rows.Add("Vijay", 6500.00, "IT");
            ds.Tables.Add(dt);
            dt = new DataTable();
            dt.Columns.Add("StudentID", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Marks", typeof(int));
            dt.Columns.Add("Grade", typeof(string));
            dt.Rows.Add(1, "Suresh", 950, "A+");
            dt.Rows.Add(1, "Rama", 900, "A+");
            dt.Rows.Add(1, "Kishore", 750, "B");
            ds.Tables.Add(dt);
            divOutput.InnerHtml = ds.GetJSON();


        }

    }


    public static class DataSetExt
    {
        public static string GetJSON(this DataSet ds)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ArrayList root = new ArrayList();
            List<Dictionary<string, object>> table;
            Dictionary<string, object> data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }
            
            return serializer.Serialize(root);
        }
    }
}

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">
    <asp:Button ID="btnGetJSON" runat="server" Text="Get JSON" OnClick="btnGetJSON_Click" />
    <br /><br />
    <div id="divOutput" runat="server">
        
    </div>
    </form>
</body>
</html>

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

This example shows you how to export datatable or dataset data to excel in asp.net and c#. By using EPPlus.dll we can easily export datatable or dataset data to excel. You can merge cells, give background color and can format the cell text in excel using EPPlus.dll in c# and asp.net

In the below example we have a dataset contains student details and product details. By using EPPlus.dll we will export the data to excel. Datatable1 (students) data will be exported to students sheet and Datatable2 (products) data will be exported to products sheet in the same excel. And we can dynamically merge the heading of the sheet and can give the border for dynamic data.

Example
Export Datatable or Dataset data to excel

C# code

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

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        CreateExcelFile();
    }

    DataSet GetData()
    {
        DataTable dt = new DataTable("Students");
        dt.Columns.Add("StudentID", typeof(int));
        dt.Columns.Add("StudentName", typeof(string));
        dt.Columns.Add("RollNumber", typeof(int));
        dt.Columns.Add("TotalMarks", typeof(int));
        dt.Rows.Add(1, "Jame's", 101, 900);
        dt.Rows.Add(2, "Steave, Smith", 105, 820);
        dt.Rows.Add(3, "Mark\"Waugh", 109, 850);
        dt.Rows.Add(4, "Steave,\"Waugh", 110, 950);
        dt.Rows.Add(5, "Smith", 111, 910);
        dt.Rows.Add(6, "Williams", 115, 864);
        DataSet ds = new DataSet("Example-DotnetLearners");
        ds.Tables.Add(dt);

        dt = new DataTable("Prodcuts");
        dt.Columns.Add("ProductID", typeof(int));
        dt.Columns.Add("ProductName", typeof(string));
        dt.Columns.Add("UnitPrice", typeof(decimal));
        for (int i = 1; i <= 100; i++)
            dt.Rows.Add(i, "Product - " + i.ToString(), i * 1.123);
        ds.Tables.Add(dt);
        return ds;
    }

    void CreateExcelFile()
    {
        try
        {
            using (DataSet ds = GetData())
            {
                if (ds != null && ds.Tables.Count > 0)
                {
                    using (ExcelPackage xp = new ExcelPackage())
                    {
                        foreach (DataTable dt in ds.Tables)
                        {
                            ExcelWorksheet ws = xp.Workbook.Worksheets.Add(dt.TableName);

                            int rowstart = 2;
                            int colstart = 2;
                            int rowend = rowstart;
                            int colend = colstart + dt.Columns.Count;

                            ws.Cells[rowstart, colstart, rowend, colend].Merge = true;
                            ws.Cells[rowstart, colstart, rowend, colend].Value = dt.TableName;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Font.Bold = true;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);

                            rowstart += 2;
                            rowend = rowstart + dt.Rows.Count;
                            ws.Cells[rowstart, colstart].LoadFromDataTable(dt, true);
                            int i = 1;
                            foreach (DataColumn dc in dt.Columns)
                            {
                                i++;
                                if (dc.DataType == typeof(decimal))
                                    ws.Column(i).Style.Numberformat.Format = "#0.00";
                            }
                            ws.Cells[ws.Dimension.Address].AutoFitColumns();



                            ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Top.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Bottom.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Left.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                        }
                        Response.AddHeader("content-disposition", "attachment;filename=" + ds.DataSetName + ".xlsx");
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.BinaryWrite(xp.GetAsByteArray());
                        Response.End();
                    }
                }
            }
        }
        catch
        {
            throw;
        }
    }
}

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>
        <asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />
    </div>
    </form>
</body>
</html>

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

This example shows you how to insert data from dataset or datatble to sql table using sql bulk copy in c#.

Dataset
sql bulk copy dataset

C# Code

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = GetData();
    SqlConnection con = new SqlConnection(@"data source=.\sqlserver; user id=sa; password=123; database=Sample;");
    SqlBulkCopy bulk = new SqlBulkCopy(con);
    bulk.DestinationTableName = "tblStudents";
    foreach (DataColumn col in ds.Tables[0].Columns)
        bulk.ColumnMappings.Add(col.ColumnName, col.ColumnName);
    con.Open();
    bulk.WriteToServer(ds.Tables[0]);
    con.Close();
}

DataSet GetData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("StudentID", typeof(int));
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("RollNumber", typeof(int));
    dt.Columns.Add("TotalMarks", typeof(int));
    dt.Rows.Add(1, "Jame's", 101, 900);
    dt.Rows.Add(2, "Steave Smith", 105, 820);
    dt.Rows.Add(3, "Mark Waugh", 109, 850);
    dt.Rows.Add(4, "Steave Waugh", 110, 950);
    dt.Rows.Add(5, "Smith", 111, 910);
    dt.Rows.Add(6, "Williams", 115, 864);
    DataSet ds = new DataSet();
    ds.Tables.Add(dt);
    return ds;
}

SQL table before data inserted
SQL table before data inserted

SQL table after C# datatable/dataset data inserted using sql bulk copy
SQL table after C# datatable/dataset data inserted using sql bulk copy

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

This example shows you how to read xml file node value in c#. By using XmlDocument we can load xml file(xml.Load(xmlfilepath)) or xml string(xml.LoadXml(xmlstring)), then xml.SelectNodes() will return the XmlNodeList. foreach of XmlNodeList will run loop on each XmlNode and XmlNod[NodeName].InnerText will return the value of the node.

Input XML Strin

private string GetXML()
{
    return @"<?xml version='1.0' encoding='UTF-8' ?>
    <EmployeeList>
        <Employee>
        <Name>James</Name>
        <DOJ>10/05/2014</DOJ>
        </Employee>
        <Employee>
        <Name>Smith</Name>
        <DOJ>06/03/2013</DOJ>
        </Employee>
        <Employee>
        <Name>Williams</Name>
        <DOJ>02/01/2013</DOJ>
        </Employee>
    </EmployeeList>";
}

Reading XML value

protected void Page_Load(object sender, EventArgs e)
{
    string strXML = GetXML();

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(strXML);

    XmlNodeList xNodeList = xml.SelectNodes("/EmployeeList/Employee");
    foreach (XmlNode xNode in xNodeList)
    {
        string employeeName = xNode["Name"].InnerText;
        string DOJ = xNode["DOJ"].InnerText;
        Response.Write("Employee Name: " + employeeName + "<br/>DOJ: " + DOJ + "<br/><br/>");
    }
}

Output
reading xml using c#

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

This example shows you how to create a csv file in c# and how to export datatable or dataset to csv file in c#. While writing csv file if input data contains double quote(") or comma(,) then csv file will not be generated properly. To overcome this issue we have written a custom method "FormatCSV" in the below example.

Datatable

Output

CS Page Code

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;
using System.IO;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            DataTable dt = GetData();
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                    sb.Append(FormatCSV(dr[dc.ColumnName].ToString()) + ",");
                sb.Remove(sb.Length - 1, 1);
                sb.AppendLine();
            }
            File.WriteAllText("E:\\Sample\\SampleCSV.csv", sb.ToString());
        }

        DataTable GetData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("StudentID", typeof(int));
            dt.Columns.Add("StudentName", typeof(string));
            dt.Columns.Add("RollNumber", typeof(int));
            dt.Columns.Add("TotalMarks", typeof(int));
            dt.Rows.Add(1, "Jame's", 101, 900);
            dt.Rows.Add(2, "Steave, Smith", 105, 820);
            dt.Rows.Add(3, "Mark\"Waugh", 109, 850);
            dt.Rows.Add(4, "Steave,\"Waugh", 110, 950);
            dt.Rows.Add(5, "Smith", 111, 910);
            dt.Rows.Add(6, "Williams", 115, 864);
            return dt;
        }

        public static string FormatCSV(string input)
        {
            try
            {
                if (input == null)
                    return string.Empty;

                bool containsQuote = false;
                bool containsComma = false;
                int len = input.Length;
                for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
                {
                    char ch = input[i];
                    if (ch == '"')
                        containsQuote = true;
                    else if (ch == ',')
                        containsComma = true;
                }

                if (containsQuote && containsComma)
                    input = input.Replace("\"", "\"\"");

                if (containsComma)
                    return "\"" + input + "\"";
                else
                    return input;
            }
            catch
            {
                throw;
            }
        }

    }

}

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

LINQ Aggregate function is used to perform calucalation over sequance/list of values. Below examples will show you how to get SUM, MAX, MIN, COUNT using LINQ Aggregate function.

Example

1. Get sum of numbers in int arrary using LINQ Aggregate function.

int[] intary = { 5, 10, 15, 20 };
int intsum = intary.Aggregate((i, j) => i + j);

Output
//50


2. Get max value usage LINQ Aggregate function.

int[] intary = { 21, 150, 5, 120,80,90 };
int maxval = intary.Aggregate((i, j) => i > j ? i : j);

Output
//150


3. Get min value usage LINQ Aggregate function.

int[] intary = { 21, 150, 5, 120,80,90 };
int minval = intary.Aggregate((i, j) => i < j ? i : j);

Output
//5


4. Get count usage LINQ Aggregate function.

int[] intary = { 21, 150, 5, 120,80,90 };
int intCount = intary.Aggregate(0, (i, j) => i = i + 1);

Output
//6


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

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
<< < 1 2 3 4 5 6 7 8 9 > >>




Search dotnetlearners.com