Pages

Showing posts with label Asp.net C#. Show all posts
Showing posts with label Asp.net C#. Show all posts

Friday, February 17, 2012

bind DropDownList using jquery ajax in asp.net

Bind DropDownList using Jquery Ajax in Asp.net

Introduction : In this article i will show you how to bind a DropDownList to avoid page refresh via a webmethod .It is very useful and many time we require to use Jquery ajax . I have here provided html and c# code behind code to understand Jquery Ajax in asp.net .

Jquery Ajax Code to Bind dropdownlist in asp.net
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function () {
  $.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8",
   data: "{}",
   url: "AjaxInJquery.aspx/GetCityData",
   dataType: "json",
   success: ajaxSucceess,
   error: ajaxError
  });
  function ajaxSucceess(response) {
   $.each(response.d, function (key, value) {
    $("#ddlCategory").append($("<option></option>").val(value.CityId).html(value.Cityname));
   });
  }
  function ajaxError(response) {
   alert(response.status + ' ' + response.statusText);
  }
 });
</script>
Html Code DropDownList
<asp:DropDownList ID="ddlCategory" runat="server">
</asp:DropDownList>
C# Code for binding Dropdownlist using Jquery Ajax
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 System.Web.Services;
using System.Data.SqlClient;

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

 }
 [WebMethod]
 public static List GetCityData()
 {
  List CityCollection = new List();
  try
  {
   DataSet Ds = GetDataSet("Select * from Countrytable");
   CityCollection = Ds.Tables[0].AsEnumerable().Select(data => new City() { CityId = (int)data["CountryID"], Cityname = (string)data["CountryName"] }).ToList();

  }
  catch (Exception) { }
  return CityCollection;
 }
 public static DataSet GetDataSet(string Query)
 {
  DataSet Ds = new DataSet();
  try
  {
   string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
   SqlConnection Con = new SqlConnection(strCon);
   SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
   Da.Fill(Ds);

  }
  catch (Exception) { }
  return Ds;
 }
}
public class City
{
 public int CityId { get; set; }
 public string Cityname { get; set; }
}

Related Other posts

Thursday, February 9, 2012

Order By Class List<> in C#

Order by Ascending and Descending class List<> in C# :

Introduction : In this article i will explain you how to sort class collection ( List<> of class ) in linq c# . I done the easy code to understand how to uses Order by Ascending and Descending of class list in linq c#.

Class example for sorting class List<> In c#: Following is the user class example with constructor in c#.
public class User
{
    public int UserId { get; set; }
    public string Firstname { get; set; }
    public User(int userId, string firstname)
    {
        UserId = userId;
        Firstname = firstname;
    }
}
Ascending and Descending Sorting class list in linq C#:
List<User> UserList = new List<User>(); 

UserList.Add(new User(1, "bimal"));
UserList.Add(new User(2, "punit"));
UserList.Add(new User(3, "amit"));

UserList = UserList.OrderBy(x => x.Firstname).ToList();  //Ascending Sorted the class list using linq.
UserList = UserList.OrderByDescending(x => x.Firstname).ToList();  // Descending Sorted the class list using linq.


Related Other posts

Add,Update,delete DetailsView in asp.net c#

Add,Update,Delete,paging with DetailsView in asp.net c#
Introduction: In this article i will show you how to bind DetailsView in asp.net c# . I have implemented all operation like paging ,add ,edit and delete in DetailsView in asp.net c# . In following i have written the Css class to format the DetaildView.  
Html Code for DetailsView in asp.net :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DetailView.aspx.cs" Inherits="HamidSite.DetailView" %>

<!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>
    <style type="text/css">
        .DetailsViewClass
        {
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
            color: #333333;
            border-width: 1px;
            border-color: #999999;
            border-collapse: collapse;
            border-style: solid;
        }
        .Header
        {
            background: #b5cfd2;
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #999999;
        }
        .Foter
        {
            background: #dcddc0;
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #999999;
        }
        .btn
        {
            background: #ffffff;
            border-width: 1px;
            padding: 2px;
            border-style: solid;
            border-color: #999999;
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
        }
        .textbox
        {
            border-width: 1px;
            padding: 1px;
            border-style: solid;
            border-color: #999999;
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
            width: 100px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DetailsView ID="DetailsViewExample" AllowPaging="true" AutoGenerateRows="false"
            runat="server" Height="50px" CssClass="DetailsViewClass" CellPadding="4" OnPageIndexChanging="DetailsViewExample_PageIndexChanging"
            OnItemCommand="DetailsViewExample_ItemCommand1" OnItemUpdating="DetailsViewExample_ItemUpdating"
            OnModeChanging="DetailsViewExample_ModeChanging" OnItemInserting="DetailsViewExample_ItemInserting"
            Width="270px" OnItemDeleting="DetailsViewExample_ItemDeleting">
            <Fields>
                <asp:TemplateField HeaderText="First Name">
                    <ItemTemplate>
                        <asp:Label ID="lblID" Text='<%# Eval("ID") %>' Visible="false" runat="server"></asp:Label>
                        <asp:Label ID="lblFirstName" Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="lblIDEdit" Text='<%# Eval("ID") %>' Visible="false" runat="server"></asp:Label>
                        <asp:TextBox ID="txtFirstname" Text='<%# Eval("FirstName") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                    <ItemTemplate>
                        <asp:Label ID="lblLastName" Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtLastName" Text='<%# Eval("LastName") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lbldob" Text='<%# Eval("City") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCity" Text='<%# Eval("City") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Address">
                    <ItemTemplate>
                        <asp:Label ID="lblAddress" Text='<%# Eval("Address") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtAddress" Text='<%# Eval("Address") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Pin No">
                    <ItemTemplate>
                        <asp:Label ID="lblPinNo" Text='<%# Eval("PinNo") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtPinNo" Text='<%# Eval("PinNo") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile No">
                    <ItemTemplate>
                        <asp:Label ID="lblMobileNo" Text='<%# Eval("MobileNo") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtMobileNo" Text='<%# Eval("MobileNo") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField Visible="true" ShowInsertButton="true" ShowCancelButton="true"
                    ShowDeleteButton="true" ShowEditButton="true" />
            </Fields>
            <PagerStyle CssClass="Foter" />
            <FieldHeaderStyle Width="80px" CssClass="Header" />
        </asp:DetailsView>
    </div>
    </form>
</body>
</html>

C# Code for DetailsView in asp.net c# :
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 System.Data.SqlClient;

namespace HamidSite
{
    public partial class DetailView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindDetailtView();
            }
        }
        private void bindDetailtView()
        {
            try
            {
                DataSet Ds = GetDataSet("Select * from Employee");
                DetailsViewExample.DataSource = Ds;
                DetailsViewExample.DataBind();
            }
            catch (Exception ex) { throw ex; }
        }
        private DataSet GetDataSet(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);

            }
            catch (Exception) { }
            return Ds;
        }
        private void ExecuteQuery(string Query)
        {
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
                SqlConnection Con = new SqlConnection(strCon);
                Con.Open();
                SqlCommand cmd = new SqlCommand(Query, Con);
                cmd.ExecuteNonQuery();
                Con.Close();
            }
            catch (Exception) { }
        }
        protected void DetailsViewExample_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
        {
            DetailsViewExample.PageIndex = e.NewPageIndex;
            bindDetailtView();
        }
        protected void DetailsViewExample_ItemCommand1(object sender, DetailsViewCommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "Edit":
                    DetailsViewExample.ChangeMode(DetailsViewMode.Edit);
                    bindDetailtView();
                    break;
                case "Cancel":
                    DetailsViewExample.ChangeMode(DetailsViewMode.ReadOnly);
                    bindDetailtView();
                    break;
                case "New":
                    DetailsViewExample.ChangeMode(DetailsViewMode.Insert);
                    bindDetailtView();
                    break;
            }
        }
        protected void DetailsViewExample_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
        }
        protected void DetailsViewExample_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            TextBox txtFirstname = (TextBox)DetailsViewExample.FindControl("txtFirstname");
            TextBox txtLastName = (TextBox)DetailsViewExample.FindControl("txtLastName");
            TextBox txtCity = (TextBox)DetailsViewExample.FindControl("txtCity");
            TextBox txtAddress = (TextBox)DetailsViewExample.FindControl("txtAddress");
            TextBox txtPinNo = (TextBox)DetailsViewExample.FindControl("txtPinNo");
            TextBox txtMobileNo = (TextBox)DetailsViewExample.FindControl("txtMobileNo");
            Label lblIDEdit = (Label)DetailsViewExample.FindControl("lblIDEdit");

            string Query = "Update Employee Set FirstName='" + txtFirstname.Text + "' ,LastName ='" + txtLastName.Text + "' ,City ='" + txtCity.Text + "',Address='" + txtAddress.Text + "',PinNo='" + txtPinNo.Text + "',MobileNo='" + txtMobileNo.Text + "' where ID =" + lblIDEdit.Text;
            ExecuteQuery(Query);
            DetailsViewExample.ChangeMode(DetailsViewMode.ReadOnly);
            bindDetailtView();
        }
        protected void DetailsViewExample_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            TextBox txtFirstname = (TextBox)DetailsViewExample.FindControl("txtFirstname");
            TextBox txtLastName = (TextBox)DetailsViewExample.FindControl("txtLastName");
            TextBox txtCity = (TextBox)DetailsViewExample.FindControl("txtCity");
            TextBox txtAddress = (TextBox)DetailsViewExample.FindControl("txtAddress");
            TextBox txtPinNo = (TextBox)DetailsViewExample.FindControl("txtPinNo");
            TextBox txtMobileNo = (TextBox)DetailsViewExample.FindControl("txtMobileNo");
            string Query = "Insert into Employee ([FirstName] ,[LastName] ,[City] ,[Address] ,[PinNo] ,[MobileNo]) values ('" + txtFirstname.Text + "' ,'" + txtLastName.Text + "' ,'" + txtCity.Text + "','" + txtAddress.Text + "','" + txtPinNo.Text + "','" + txtMobileNo.Text + "')";
            ExecuteQuery(Query);
            DetailsViewExample.ChangeMode(DetailsViewMode.ReadOnly);
            bindDetailtView();
        }
        protected void DetailsViewExample_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
        {
            Label lblID = (Label)DetailsViewExample.FindControl("lblID");
            string Query = "Delete from Employee where ID =" + lblID.Text;
            ExecuteQuery(Query);
            bindDetailtView();
        }
    }
}

Related Other posts

Sunday, January 29, 2012

Export gridview to excel in Asp.net

Export gridview to excel in Asp.net :

Introduction : In this article i will show you how to export GridView to excel file. Many times we require to export the GridView to excel sheet file.I have here written following code in asp.net c# to export the gridview control to excel sheet file.

Html code for gridview export to excel sheet :
<asp:GridView ID="GridViewExample" runat="server" AutoGenerateColumns="False" BackColor="White"
    BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
    <Columns>
        <asp:TemplateField HeaderText="City Name" SortExpression="Name" FooterStyle-Width="200px"
            ItemStyle-Width="200px">
            <ItemTemplate>
                <asp:Label ID="lblCityName" Text='<%#Bind("Name")%>' runat="server"></asp:Label>
            </ItemTemplate>
            <FooterStyle Width="200px"></FooterStyle>
            <ItemStyle Width="200px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="STD Code" SortExpression="STDCode" FooterStyle-Width="100px"
            ItemStyle-Width="100px">
            <ItemTemplate>
                <asp:Label ID="lblSTDCOde" Text='<%#Bind("STDCode")%>' runat="server"></asp:Label>
            </ItemTemplate>
            <FooterStyle Width="100px"></FooterStyle>
            <ItemStyle Width="100px"></ItemStyle>
        </asp:TemplateField>
    </Columns>
    <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" />
</asp:GridView>
<asp:Button ID="btnExport" BackColor="#003399" Text="Export To Excel" runat="server"
    OnClick="btnExport_Click" />
C# Code to export the gridview to excel sheet :
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.IO;

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

        private void BindGridView()
        {
            try
            {
                DataTable Dt = GetDataTable("Select Name ,stdcode from citytable");
                GridViewExample.DataSource = Dt;
                GridViewExample.DataBind();

            }
            catch (Exception)
            {
                throw;
            }
        }
        private DataTable GetDataTable(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True;";  //Conntection String
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);
            }
            catch (Exception) { }
            return Ds.Tables[0];
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExample.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";

            StringWriter StringWriter = new System.IO.StringWriter();
            HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

            GridViewExample.RenderControl(HtmlTextWriter);
            Response.Write(StringWriter.ToString());
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    }
}

Related Other posts

Saturday, January 28, 2012

Sorting, Paging, Add, Update, Delete in GridView asp.net c#

Sorting, Paging, Add, Update, Delete in GridView asp.net c#
Introduction : In this article i will show full functional Gridview with Sorting, Paging , Add ,Update ,delete operation .The GridView control is used to display the values of a data source in a table. It is very useful asp.net control .Here I have written the code for Sorting , Paging , Update , Delete , Add with footer row . 
The Code for All operations in GridVeiw that i have written is very easy understand and easy to implement in you application .

Html Code For Gridview with Sorting, Paging , Add ,Update ,delete operation In Asp.net: 
<table>
    <tr>
        <td>
            <asp:Label ID="lblmsg" runat="server" ForeColor="Red"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:GridView AllowSorting="True" AllowPaging="True" PageSize="3" ID="GVCity" runat="server"
                AutoGenerateColumns="False" OnRowCommand="GVCity_RowCommand" OnPageIndexChanging="GVCity_PageIndexChanging"
                OnSorting="GVCity_Sorting" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
                BorderWidth="1px" CellPadding="4">
                <Columns>
                    <asp:TemplateField HeaderText="City Name" SortExpression="Name" FooterStyle-Width="200px"
                        ItemStyle-Width="200px">
                        <ItemTemplate>
                            <asp:Label ID="lblCityName" Text='<%#Bind("Name")%>' runat="server"></asp:Label>
                            <asp:Label ID="lblCityId" Visible="false" Text='<%#Bind("CityId")%>' runat="server"></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEditCityName" Text='<%#Bind("Name")%>' runat="server"></asp:TextBox>
                            <asp:Label ID="lblCityIdEdit" Visible="false" Text='<%#Bind("CityId")%>' runat="server"></asp:Label>
                            <asp:RequiredFieldValidator ID="rfvEditCityname" ValidationGroup="Edit" runat="server"
                                SetFocusOnError="true" Display="Dynamic" ControlToValidate="txtEditCityName"
                                ErrorMessage="Please , Enter City Name."></asp:RequiredFieldValidator>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtFooterCityName" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rfvFooterCityname" ValidationGroup="Footer" runat="server"
                                SetFocusOnError="true" Display="Dynamic" ControlToValidate="txtFooterCityName"
                                ErrorMessage="Please , Enter City Name."></asp:RequiredFieldValidator>
                        </FooterTemplate>
                        <FooterStyle Width="200px"></FooterStyle>
                        <ItemStyle Width="200px"></ItemStyle>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="STD Code" SortExpression="STDCode" FooterStyle-Width="100px"
                        ItemStyle-Width="100px">
                        <ItemTemplate>
                            <asp:Label ID="lblSTDCOde" Text='<%#Bind("STDCode")%>' runat="server"></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEditSTDCOde" Text='<%#Bind("STDCode")%>' runat="server"></asp:TextBox>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtFooterSTDCOde" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <FooterStyle Width="100px"></FooterStyle>
                        <ItemStyle Width="100px"></ItemStyle>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            Actions
                        </HeaderTemplate>
                        <FooterTemplate>
                            <table cellpadding="2">
                                <tr>
                                    <td>
                                        <asp:ImageButton ID="imgBtnAdd" CssClass="imgButton" ImageUrl="~/Images/save.png"
                                            runat="server" CommandName="AddSave" ValidationGroup="Footer" ToolTip="Save"
                                            CausesValidation="true" />
                                        <asp:ImageButton ID="ImageBtnCancel" CssClass="imgButton" runat="server" ImageUrl="~/Images/cancel.gif"
                                            CommandName="AddCancel" ToolTip="Cancel" CausesValidation="false" />
                                    </td>
                                </tr>
                            </table>
                        </FooterTemplate>
                        <EditItemTemplate>
                            <table cellpadding="2">
                                <tr>
                                    <td>
                                        <asp:ImageButton ID="imgBtnEditSave" AlternateText="Save" CssClass="imgButton" runat="server"
                                            CommandName="EditSave" ToolTip="Save" ValidationGroup="Edit" CausesValidation="true"
                                            ImageUrl="~/Images/save.png" />
                                        <asp:ImageButton ID="ImageEditCancel" AlternateText="Cancel" CssClass="imgButton"
                                            runat="server" CommandName="EditCancel" CausesValidation="false" ImageUrl="~/Images/cancel.gif"
                                            ToolTip="Cancel" />
                                    </td>
                                </tr>
                            </table>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <table cellpadding="2">
                                <tr>
                                    <td>
                                        <asp:ImageButton ID="imgLanEdit" ImageUrl="~/Images/edit.gif" CssClass="imgButton"
                                            runat="server" CommandName="CityEdit" ToolTip="Edit" />
                                        <asp:ImageButton ID="ImgBtnDelete" ImageUrl="~/Images/delete.gif" CssClass="imgButton"
                                            runat="server" CommandName="CityDelete" ToolTip="Delete" />
                                    </td>
                                </tr>
                            </table>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                <RowStyle BackColor="White" ForeColor="#330099" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                <SortedAscendingCellStyle BackColor="#FEFCEB" />
                <SortedAscendingHeaderStyle BackColor="#AF0101" />
                <SortedDescendingCellStyle BackColor="#F6F0C0" />
                <SortedDescendingHeaderStyle BackColor="#7E0000" />
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="imgExperiencetInsert" runat="server" Text="Insert Record" OnClick="imgExperiencetInsert_Click" />
        </td>
    </tr>
</table>
C# Code For Gridview with Sorting, Paging , Add ,Update ,delete operation In Asp.net: 
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 System.Data.SqlClient;

namespace HamidSite
{
    public partial class GridviewExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblmsg.Text = "";
            if (!IsPostBack)
            {
                BindGridView();
            }
        }
        private string SortDirection
        {
            get
            {
                if (ViewState["SortDirection"] != null)
                    return (String)ViewState["SortDirection"];
                else return "ASC";
            }
            set
            {
                ViewState["SortDirection"] = value;
            }
        }
        private string SortExpression
        {
            get
            {
                if (ViewState["SortExpression"] != null)
                    return ViewState["SortExpression"].ToString();
                else return null;
            }
            set
            {
                ViewState["SortExpression"] = value;
            }
        }
        private void BindGridView()
        {
            try
            {
                DataTable Dt = GetDataTable("Select Name ,stdcode ,Cityid from citytable");
                DataView DV = Dt.DefaultView;

                if (SortExpression != null)
                {
                    DV.Sort = SortExpression + " " + SortDirection;
                }

                GVCity.DataSource = DV;
                GVCity.DataBind();
                if (DV.Count == 0)
                {
                    imgExperiencetInsert.Visible = false;
                }
                else
                {
                    imgExperiencetInsert.Visible = true;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        private DataTable GetDataTable(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=Servername;Initial Catalog=Test;Integrated Security=True;";  //Conntection String
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);
            }
            catch (Exception) { }
            return Ds.Tables[0];
        }
        private int ExecuteQuery(string Query)
        {
            int RowAffected = 0;
            try
            {
                string strCon = @"Data Source=Servername;Initial Catalog=Test;Integrated Security=True;";  //Conntection String
                SqlConnection Con = new SqlConnection(strCon);
                Con.Open();
                SqlCommand cmd = new SqlCommand(Query, Con);
                RowAffected = (int)cmd.ExecuteNonQuery();
                Con.Close();
            }
            catch (Exception) { }
            return RowAffected;
        }
        /// 
        /// Edit , Update , Delete , Cancel in Gridview using RowCommand in c# Code.
        ///         
        protected void GVCity_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "AddCancel":
                    GVCity.EditIndex = -1;
                    imgExperiencetInsert.Enabled = true;
                    GVCity.ShowFooter = false;
                    BindGridView();
                    break;
                case "AddSave":

                    GridViewRow grvAdd = ((GridViewRow)((DataControlFieldCell)((ImageButton)e.CommandSource).Parent).Parent);
                    TextBox txtFooterCityName = (TextBox)grvAdd.FindControl("txtFooterCityName");
                    TextBox txtFooterSTDCOde = (TextBox)grvAdd.FindControl("txtFooterSTDCOde");

                    string InsertQuery = "Insert into cityTable(Name,STDCode) Values('" + txtFooterCityName.Text.Trim() + "','" + txtFooterSTDCOde.Text.Trim() + "')";
                    if (ExecuteQuery(InsertQuery) > 0)
                    {
                        lblmsg.Text = "City Inserted Successfully";
                        imgExperiencetInsert.Enabled = true;
                    }

                    GVCity.ShowFooter = false;
                    BindGridView();

                    break;
                case "CityDelete":
                    GridViewRow grv = ((GridViewRow)((DataControlFieldCell)((ImageButton)e.CommandSource).Parent).Parent);

                    if (grv != null)
                    {
                        Label lblCityId = (Label)grv.FindControl("lblCityId");
                        String DeleteQuery = "Delete from cityTable where cityid =" + lblCityId.Text;
                        
                        if (ExecuteQuery(DeleteQuery) > 0)
                        {
                            lblmsg.Text = "City Deleted Successfully";

                        }
                        BindGridView();
                        break;
                    }

                    break;
                case "CityEdit":
                    GridViewRow grvEdit = ((GridViewRow)((DataControlFieldCell)((ImageButton)e.CommandSource).Parent).Parent);
                    GVCity.EditIndex = grvEdit.RowIndex;
                    BindGridView();
                    break;

                case "EditSave":
                    GridViewRow grvSaveEdit = ((GridViewRow)((DataControlFieldCell)((ImageButton)e.CommandSource).Parent).Parent);

                    TextBox txtEditCityName = (TextBox)grvSaveEdit.FindControl("txtEditCityName");
                    TextBox txtEditSTDCOde = (TextBox)grvSaveEdit.FindControl("txtEditSTDCOde");
                    Label lblCityIdEdit = (Label)grvSaveEdit.FindControl("lblCityIdEdit");

                    string queryUpdate = "update cityTable set Name = '" + txtEditCityName.Text.Trim() + "', STDCode ='" + txtEditSTDCOde.Text.Trim() + "' where cityid=" + lblCityIdEdit.Text;
                    if (ExecuteQuery(queryUpdate) > 0)
                    {
                        lblmsg.Text = "City Updated Successfully";
                        imgExperiencetInsert.Enabled = true;
                    }
                    
                    GVCity.EditIndex = -1;
                    BindGridView();

                    break;
                case "EditCancel":
                    GVCity.EditIndex = -1;
                    BindGridView();
                    break;
            }
        }
        protected void imgExperiencetInsert_Click(object sender, EventArgs e)
        {
            imgExperiencetInsert.Enabled = false;
            GVCity.ShowFooter = true;
            GVCity.EditIndex = -1;
            BindGridView();
        }
        protected void GVCity_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GVCity.PageIndex = e.NewPageIndex;
            BindGridView();
        }
        /// 
        /// Gridview Sorting Code in c#
        ///        
        protected void GVCity_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (SortExpression != null)
            {
                if (SortExpression == e.SortExpression && SortDirection == "ASC")
                    SortDirection = "DESC";
                else
                    SortDirection = "ASC";
            }
            SortExpression = e.SortExpression;
            BindGridView();
        }
    }
}


Related Other posts

Wednesday, January 25, 2012

Pass arguments to String.Format method in c#

Pass arguments to String.Format method in c# 

Introduction : In this article i will show you how to pass the arguments to String.Format method in c# . You need to pass comma separated list of arguments to the string.Format method .There must be argument for each of the place holders .

Following is the example of String.Format in c# :
 
 string Name ="Seta Hamid ";
 string Country ="India";          
 Response.Write( String.Format("My Name is {0}. I am from {1}.", Name, Country));

Output of the string.Format C#.
 
My Name is Seta Hamid . I am from India. 


Related Other posts

Wednesday, January 11, 2012

Chart Control in asp.net 4.0

Chart Control in asp.net 4.0  

Introduction : In this article i will show you how to add Chart control in asp.net 4.0 and how to bind chart control in asp.net with Dataset .You just need to drag the chart control in aspx page so following assembly will be register in your web page and corresponding httpHandlers will be added in web config too .

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
Code For Bind Chart Control In asp.net : I have following complete html and code behind code for binding Chart control in c# asp.net. I have here created Bar chart control in asp.net.

HTML Code For Chart Control In asp.net :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChartControl.aspx.cs" Inherits="HamidSite.ChartControl" %>

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<!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:Chart ID="ChartControlTest" runat="server" Width="706px" Height="367px">
            <Series>
                <asp:Series Name="SeriesTest" IsValueShownAsLabel="true" Legend="LegendTest" ChartArea="ChartAreaTest"
                    XValueMember="MonthName" YValueMembers="Amount">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartAreaTest" Area3DStyle-LightStyle="Simplistic" AlignmentStyle="AxesView"
                    BorderDashStyle="Solid" Area3DStyle-Enable3D="true">
                </asp:ChartArea>
            </ChartAreas>            
        </asp:Chart>
    </div>
    </form>
</body>
</html>

C# Code For Chart Control in asp.net :
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 System.Data.SqlClient;

namespace HamidSite
{
    public partial class ChartControl : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindChartControl();
            }
        }
        private void BindChartControl()
        {
            DataSet Ds = GetDataSet("Select MonthName , Amount from OrderTable");
            ChartControlTest.DataSource = Ds; 
            ChartControlTest.DataBind(); 
        }
        private DataSet GetDataSet(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True;";  //Conntection String
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);
            }
            catch (Exception) { }
            return Ds;
        }
    }
}
Related Other posts

Tuesday, January 10, 2012

Check / Uncheck all checkbox in treeview using jquery in asp.net

Check / Uncheck all checkbox in treeview using jquery in asp.net

Introduction : In this article i will show you how check all checkboxes in treeview using Jquery in asp.net .It is very easy just you need add code and replace id as per treeview control . For the binding the Treeview control in asp.net you can visits my previous post bind treeview in-asp.net .
Jquery for check / uncheck all checkboxes in treeview in c# :

Following is jquery code for check or uncheck all checkboxes in treeview control and HTML code in asp.net .

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

<!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="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" >

        $(document).ready(function () {

            $("div[id $= treeviwExample] input[type=checkbox]").click(function () {
                $(this).closest("table").next("div").find("input[type=checkbox]").attr("checked", this.checked);
            });

        });    
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TreeView ID="treeviwExample" ShowCheckBoxes="All"  runat="server" ImageSet="Arrows">
            <HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
            <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px" VerticalPadding="0px" />            
        </asp:TreeView>
    </div>
    </form>
</body>
</html>


Related Other posts

Monday, January 9, 2012

Bind Treeview in asp.net c# using dataset

Bind Treeview in asp.net c# using dataset
Introduction : In this article i will show you how to bind treeview in c# using dataset . I have created complete code to bind the treeview and also table structure in image which require for the treeview control to bind in asp.net c# using dataset .
Table structure :
HTML code treeview in asp.net :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeViewControl.aspx.cs"
    Inherits="HamidSite.TreeViewControl" %>

<!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:TreeView ID="treeviwExample"  runat="server" ImageSet="Arrows">
            <HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
            <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px" VerticalPadding="0px" />            
        </asp:TreeView>
    </div>
    </form>
</body>
</html>

C# Code treeview control in asp.net :
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 System.Data.SqlClient;

namespace HamidSite
{
    public partial class TreeViewControl : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                BindTreeViewControl();
            }
        }
        private void BindTreeViewControl()
        {
            try
            {
                DataSet ds = GetDataSet("Select ProductId,ProductName,ParentId from ProductTable");
                DataRow[] Rows = ds.Tables[0].Select("ParentId IS NULL"); // Get all parents nodes
                for (int i = 0; i < Rows.Length; i++)
                {
                    TreeNode root = new TreeNode(Rows[i]["ProductName"].ToString(), Rows[i]["ProductId"].ToString());
                    root.SelectAction = TreeNodeSelectAction.Expand;
                    CreateNode(root, ds.Tables[0]);
                    treeviwExample.Nodes.Add(root);
                }
            } catch (Exception Ex) { throw Ex; }
        }

        public void CreateNode(TreeNode node , DataTable Dt)
        {
            DataRow[] Rows = Dt.Select("ParentId =" + node.Value);            
            if (Rows.Length == 0) { return; }
            for (int i = 0; i < Rows.Length; i++)
            {
                TreeNode Childnode = new TreeNode(Rows[i]["ProductName"].ToString(), Rows[i]["ProductId"].ToString());
                Childnode.SelectAction = TreeNodeSelectAction.Expand;
                node.ChildNodes.Add(Childnode);
                CreateNode(Childnode, Dt);
            }
        }
        private DataSet GetDataSet(string Query)
        {           
            DataSet Ds = new DataSet();
            try {
                string strCon = @"Data Source=Servername;Initial Catalog=Test;Integrated Security=True"; 
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);
            } catch (Exception) { }
            return Ds; 
        }
    }
}

For Check / Uncheck Checkboxes in treeview control using jquery you can visit following post :- Check / Uncheck Checkboxes in treeview control using jquery

Related Other posts

Saturday, January 7, 2012

Merge word document files in asp.net c#

Merge word document files in asp.net c#

Introduction : This article show you how to merge or combine two more doc files in Asp.net using C# .
I have created one function to merge multiple word file in c# .it is very easy to use .You just need to pass word file path arrays and save file path . Then i will save  merged word document file .

Add following dll reference to your application :

Microsoft.Office.Interop.Word


Code for merge word doc files : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;

namespace HamidSite
{
    public partial class MergerWorddocs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string[] DocsFiles = new string[] { @"C:\Merfiles\Doc1.docx", @"C:\Merfiles\Doc2.docx" };
            string PathToSave =Server.MapPath("MergesDocs/MergeDoc.docx");
            Merge(DocsFiles,PathToSave,true);
            
        }
        public void Merge(string[] filesToMerge, string fileSavePath, bool insertPageBreaks)
        {  
            object missing = System.Type.Missing;
            object pageBreak = WdBreakType.wdPageBreak;
            object outputFile = fileSavePath;
           
            Application wordApplication = new Application();
            try
            {                
                Document wordDocument = wordApplication.Documents.Add(ref missing, ref missing , ref missing , ref missing);                           
                Selection selection = wordApplication.Selection;
               
                foreach (string docFile in filesToMerge)
                {
                    selection.InsertFile(docFile , ref missing , ref missing , ref missing , ref missing);
                    if (insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }               
                wordDocument.SaveAs(ref outputFile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                wordDocument = null;
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
            catch (Exception ex) { throw ex; }           
        }
    }
} 



Related Other posts

Friday, January 6, 2012

DOC file to RTF format in asp.net C#.

DOC file to RTF format in asp.net C#.

Introduction : This article describe how you can convert the DOC file to RTF format in asp.net using c# language .

Code For Doc to RTF: I have created one function to convert DOC file to RTF format in c# . You need to pass just doc file path to it and it save the .RTF format file .
First you need to add reference of Microsoft.Office.Interop.Word.dll dll in project .
Microsoft.Office.Interop.Word.dll

Function For Conversion Doc To RTF :
public void ConvertDocToRTF(string DocPath)
{        
        //Creare object of documnet .
        Document document = new Document();
        try
        {
          //Load doc file from given path
          document.LoadFromFile(DocPath);
         //Save doc file. It will convert to .Rtf format .
          document.SaveToFile("Tesfile.rtf", FileFormat.Rtf);
        }
        catch (Exception) { throw; }
}

Call Function :
ConvertDocToRTF("MyDocFilePath");


Related Other posts

Thursday, January 5, 2012

Send Mail Using gmail In asp.net c#

Send Mail Using gmail In asp.net c#.

Introduction : In this article i will show you how to send mail in asp.net using gmail account.It is very simple just you need to pass your gmail account email address and password in System.Net.NetworkCredential() . And also you need to set host= smtp.gmail.com ,port =587 .I have following code to send mail using gmail account in asp.net c# .

protected void btnSendMail_Click1(object sender, EventArgs e)
    {        
        string myEmailAddress = "your gmail account";
        string mypwd = "your gmail account password";
        string toEmailAddress = "to email address";
        string subject = "Test Subject";
        string mailbody = "Test body";
       
        var client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new System.Net.NetworkCredential(myEmailAddress, mypwd),
            EnableSsl = true
        };
        client.Send(myEmailAddress, toEmailAddress, subject, mailbody);      
    }


Related Other posts

Wednesday, January 4, 2012

Redirect One website to another website automatically

Redirect One website to another website

Introduction : In this article i will show how to redirect one website to another website . Many times we require that some one visit  www.xyz.com  then he should be redirect to another site for that you need add peace of java-script code and it automatically redirect to another site .

<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
       location.replace("http://www.google.com");         
    </script>
</head>


Related Other posts

Tuesday, December 27, 2011

RadioButtonList Control In Asp.net c#

RadioButtonList Control In Asp.net c# 
Introduction :  In this article i will show you how to bind Radiobuttonlist in asp.net c# .Radiobuttonlist control is group of Radiobutton.Many time we require to bind the data in RadioButtonList using database sql server in asp.net . I have here provided complete Html code and Code behind code for binding RadioButtonList In Asp.net c# .Following are my simple code .

Html Code :-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RadioButtonList.aspx.cs" Inherits="RadioButtonList" %>
<!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>
            <table>
                <tr> <td> <h2> RadioButtonList example</h2></td> </tr>
                <tr>
                       <td> <asp:RadioButtonList ID="rblRadiobuttonlistTest" CellPadding="1" CellSpacing="1" RepeatDirection="Vertical" runat="server"></asp:RadioButtonList>  </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Server Side 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 System.Data.SqlClient;

public partial class RadioButtonList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindRadioButtonList();
        }
    }
    private void bindRadioButtonList()
    {   try{
            DataSet Ds = GetDataSet("Select * from Countrytable");
            rblRadiobuttonlistTest.DataSource = Ds;                 // Set DataSource Here
            rblRadiobuttonlistTest.DataTextField = "CountryName";   // Assign DataText Field
            rblRadiobuttonlistTest.DataValueField = "CountryID";    // Assign Value Field
            rblRadiobuttonlistTest.DataBind();
            }  catch (Exception) { }
    }
    private DataSet GetDataSet(string Query)
    {   DataSet Ds = new DataSet();
        try{
            string strCon = @"Data Source=ServerName\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";  //Conntection String
            SqlConnection Con = new SqlConnection(strCon);
            SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
            Da.Fill(Ds);
           } catch (Exception) { }
        return Ds; 
    }
}
Conclusion : It is very easy to bind the radiobuttonlist control in asp.net .

Related Other posts

CheckBoxList example In Asp.net c#


CheckBoxList example In Asp.net c# 

Many time we require to bind the data in checkboxlist using database sql server in asp.net . I have here provided complete Html code and Code behind code for binding CheckBoxList In Asp.net c# .Following are my simple code .

Screen Shots :-

Html Code :-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Checkboxlist.aspx.cs" Inherits="Checkboxlist" %>
<!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">
    <table>
        <tr> <td> <h2>  CheckBoxList example</h2> </td> </tr>
        <tr>
            <td> <asp:CheckBoxList ID="chklisttest" runat="server"> </asp:CheckBoxList>  </td>
        </tr>
    </table>
    </form>
</body>
</html>

Code Behind :-

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 System.Data.SqlClient;

public partial class Checkboxlist : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindCheckBoxList();
        }
    }
    private void bindCheckBoxList()
    {   try
        {
            DataSet Ds = GetDataSet("Select * from Countrytable");
            chklisttest.DataSource = Ds;
            chklisttest.DataTextField = "CountryName";
            chklisttest.DataValueField = "CountryID";
            chklisttest.DataBind();
        }
        catch (Exception){}
    }
    private DataSet GetDataSet(string Query)
    {   DataSet Ds = new DataSet();
        try
        {   string strCon = @"Data Source=Servername;Initial Catalog=Test;Integrated Security=True";
            SqlConnection Con = new SqlConnection(strCon);
            SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
            Da.Fill(Ds);           
        }
        catch (Exception){}
        return Ds;
    }
}


Related Other posts

Monday, December 26, 2011

Fill Dataset In Asp.net C#

Fill DataSet In Asp.net C#

Introduction :


In this article i will show how to fill dataset from database sql server using c# language .For this i have created common methodh in which you have just pass the query and it automatically return the filled dataset .GetDataSet function contains the easy code to fill the dataset .

Calling the method :
DataSet Ds = GetDataSet("Select * from Tablename");

Method to bind dataset :
private DataSet GetDataSet(string Query)
    {
        DataSet Ds = new DataSet();
        try
        {
            
            string strCon =""; // set connetion string here ..
            SqlConnection Con = new SqlConnection(strCon);
            SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
            Da.Fill(Ds);
           
        }
        catch (Exception)
        {
        }
        return Ds;
    } 


Related Other posts