Friday, August 30, 2013

DataBinding in windows Forms in asp.net using C#.net

Title:Data binding for windows form using C#

Description:
Data Binding is the concept if providing address of memory location to a control for presenting data.This will reduce coding burden on developer and makes development faster.Below image can give the brief idea on it
Each window for will maintain binding context component.Binding context component will manage currency manager components,Currency manager will maintain record pointer to data-set table,it supports navigation and manipulations,It will place data into Bound Control.
Here the currency manager acts like mediator  between  bound control and memory block

There are two type of data binding con concepts,
1.Simple data binding
2.Complex data binding

Using Simple data binding,control can be bind to only single element.Complex data binding can be bind to more than single element

Tuesday, August 27, 2013

How to use For loop in C#.net

In this articles i will show how to use looping statement in c#.net.In this examples A program to add to textBox at run time. Here i placed one button to perform click event.
code for button click
{
int x=30;
for(int i=1;i<=10;i++)
{TextBox txt=New TextBox();
txt.Text="Txxt"+i;
txt.Location=New Point(100,x);
This.Controls.Add(txt);
x=x+30;
}
In the above code i created 10 text box using for loop condition.The for loop condition takes maximum iteration up to 10 which i was given at condition


Wednesday, August 14, 2013

Datasource Controls in Asp.net


The data source controls are available from asp.net 2.0(Not bound controls).Using this controls we can automate the task of creating data object.Normally we have to prepare data object programatically(using code).Whenever use these controls we may get some question regarding wizard approach features then one programmatic object will be created most importantly these controls provide complete customization options.The following data source controls are available in Asp.net

1.SQL Data source control
2.LINQ Data source control
3.Object Data source control
4.XML Data source control
5.Ado.net entity framework Data source control

1.Sql Data source control:
it is used to prepare data object from any SQL supported database Oracle,SqlServer,Access,My Sql,SYSbase,Informix,Ingres etc


Features:
The DS controls supports caching features . Data source controls does not Cache any data.with enable cache property of it we can add caching support.The reason to cache data is to avoid DB trips for every request.If data is cached then we retrieve data from they cache only by avoiding db.This will improve performance like anything.Different property for caching are also supported for maintaining time ,dependency etc
Conflict Detection(Concurrency control)
Using Data source controls when we manipulate data there is every possibility of occurring concurrency problems because web is for all and also our form can be accessed many users . DS controls provide conflict detection with 2 option

i)Override changes
ii)Compare all values

Wednesday, August 7, 2013

How to create and consume usercontrol without vs.net

Title:How to access user control in asp.net

Description:The use controls can be used when we require a control which can be working as per our requirement.Now i would like to explain how to access this into our web application
1.Use notepad or some other editor and write all aspx/js/html code in it.Save it with .ascx extension
2.Add the created .ascx to the current project i:e copy it into current project folder
3.Go to the page where we want to consume this control and add <%@Register--%> directive
<%@Register Tagprefix="Nit" TagName="RichBanner" src="banner.ascx"%>
4.In the same page now create controls using markup
<Nit:RichBanner ID="rbl" runat="server"/>
5.To Create a control; at run time we cannot use normal syntax for use defined control.We must use load method of page to create it

Ex:-Banner a=page.Load("Banner.ascx")
similarly unload(--) to remove the controls form  form
Remember we must add it to some container after creating it
6.Every control once designed can be placed onto an assembly
7.Only ascx with a dll will be prepared and given to user(publish required)
8.<%@ control--%> directive is used instead of <%@ page--%> and contains will be placed inside a page which contains all HTML content

Tuesday, August 6, 2013

Bind data to Asp.net text box using dropdownlist in jquery

Title: JQuery set text box value in asp.net

Description:
In recent articles we known how to implement the  Data binding concept on data  controls like grid view,Data list,list etc.Here i would like to explain how to bind data to asp.net text box while leave the focus on Drop Down List using JQuery blur function.The blur function will fire when the previous controls has lost focus.

Example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bind data to Asp.net text box using DropDownList in jquery</title>
</head>
<script type="text/javascript" src="~/jquery.min.js" ></script>
<script>
$(document).ready(function() {
$("#ddlSalesOrder").blur(function(){
var SalesOrderText = $("#ddlSalesOrder option:selected").text();
 alert(SalesOrderText);
$("#<%= txtOrderTotalAmt.ClientID %>".val(SalesOrderText); 
});
});
</script>
</head>
<body>
Amount: <asp:DropDownList ID="ddlSalesOrder" runat="server">
<asp:ListItem>100</asp:ListItem>
<asp:ListItem>125</asp:ListItem>
<asp:ListItem>150</asp:ListItem>
<asp:ListItem>175</asp:ListItem>
<asp:ListItem>200</asp:ListItem>
</asp:DropDownList>
TotalAmount:<asp:TextBox ID="txtOrderTotalAmt" runat="server"></asp:TextBox>
</body>
</html>
As you can see there is alert to confirmation for drop down selected value will come when the blur event occurs.Whenever we are using JQuery ,we should add JQuery library reference to our application.
In the above example we have taken one drop down list and text box to display the amount order .When the amount Drop down list has lost the focus ,the total Amount will be populate automatically.

Monday, July 29, 2013

2-Tier architecture in .net

1.In this architecture application required things placed into two systems is called "2-Tier Architecture" or client server application
2.Client server architecture is recommended when application is running on different systems with centralized data.in 2-tier business logic is placed with in each system,this repetition are be avoided
3.by maintaining business logic with database server in the form of stored subprogram
4.Maintain business logic with database server is called "2 and half tier architecture
5.When it comes to enterprise level the number of clients will be more (or) client will be outside organization network.In this case maintaining business logic with data base server in not recommended for following reason
i.More burden on database,it will effect the performance

Bind data to Asp.net text box using jquery

Title: JQuery bind data to asp.net text box using Blur function

Description:
As per previous articles we have gone through different kind of data binding examples using jquery in asp.net.Now here we will learn about the usage of jquery functionality for web control.

Example:
Now i would like give an example to set the data to Text box in asp.net using jquery.This application will use to  set the food orders.As per requirement we need to assign the value to text box control based on food category Id.To accomplish this task  i have utilized  Jquery script function i:e Blur() which make the functionality what ever we used inside of it

$(document).ready(function() {
$("#<%= txtOrderList.ClientID %>").blur(function(){
var orderList = $(this).val();
$("#<%= txtOrderList1.ClientID %>".val(orderList); 
});

The above script will will bind the data to text box when the other text box focus has moved.You can use this functionality as per requirement very quickly.
This article may help you a lot..Keep visit my website

Wednesday, July 24, 2013

Creating Database WithOut GUI in asp.net

Title:Create new data base using dot net framework 

1.With in object explorer right click on the database note and choose new database to open new database dialog box
2.In that new database dialog box at the database name option provide a name to the database and keep the owner as the default
3.By default one data filer and one log file are created automatically and will be shown in as table when you ant to create additional files and log files.
4.Click on add button at the bottom of the table.The table provides the first column name that can be used to specify logical name of the file .
5.File type column to specify whether the data file belongs to primary or secondary file group and the initial size column to specify initial memory to be allocated to the file
6.Use the auto growth column to specify how much memory to be incremented to the file.When it names additional memory and the maximum limit for the file.
7.To change these option click on the button on right side of the column .Auto growth that open a dialog box with in they dialog box specify the file growth and max size and click on OK button
8.Use  the column path to specify the physical path where you want to save the file to change the path ,click on the button on right side of the column path
9.After specifying the all the files required for the data base click o OK button to complete the Creation of database and click the dialog box


Tuesday, July 23, 2013

Serverside programming in Asp.net

1.All programs that are written as html/Js are executed in client system only.
2.The role of server for these programs is simply send a copy of program to client browser and its JS independent exceeds the code in client
3.Now when we write server side programs the program will be executed at server only .
4.The result will be sent back to client .All client side ans server side programs are based on execution only.
5.In web application extension are very important.
6.Many server side  environment are provided to develop server side scripting and web application

Friday, July 19, 2013

Components of .net framework

Many of the updated and code related things have discussed on er-liar. In this post i just give some basic Concepts of .net framework.
The components of .net frame work:

1.Common Language Run time(CLR)
2.Base class library
3.Framework Class Library

Components of CLR:
1.Common language specification(CLS)
2.common type system(CTS)
3.garbage collector
4.Just in time

Thursday, July 18, 2013

Bind data to RadioButtonList with arraylist in asp.net

Title:
How to bind data to web server control using array list in asp.net using c#

Description:
Array list can hold list of items of similar data type.When  we want  declare the array list with specific size,no need to set the size of array list,because it can be re sizable automatically .

Example:
The below example will show how to add data statically and dynamically to radio button through array list.But  the binding concepts are also utilize for bind data to this standard control..Later articles i would like give all methods regarding array list

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

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArrayList listNum = new ArrayList();
listNum.Add("b");
listNum.Add("h");
listNum.Add("a");
listNum.Add("k");
listNum.Add("r");
rbNumber.DataSource = listNum;
rbNumber.DataBind();
}
}
I hope it is helping for you.Thanks for coming and visit again

Monday, July 15, 2013

how to compare two xml files in asp.net using c#

Title:How to compare XML files in Asp.net using C#

Description:

Now i would like to give an examples on Comparing of XML documents using C# code.Asp.net provide an algorithm which is "hash algorithm",can be used for encryption.So based on those methods i will do the comparison of files In the below method i have use two parameters which indicates the path of XML files

Examples:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Security.Cryptography;

private void CompareXMLDocumnet(string ActualDocumnet,string GenratedDocument)
{
if (File.Exists(ActualDocumnet) && File.Exists(GenratedDocument))
{
HashAlgorithm HA = HashAlgorithm.Create();
FileStream XmlFstream1 = new FileStream(ActualDocumnet, FileMode.Open);
FileStream XmlFstream2 = new FileStream(GenratedDocument, FileMode.Open);
byte[] Actual_Xmlhash1;
byte[] Genrated_Xmlhash2;
Actual_Xmlhash1= HA.ComputeHash(XmlFstream1);
Genrated_Xmlhash2= HA.ComputeHash(XmlFstream2);
XmlFstream1.Close();
XmlFstream2.Close();
if (Convert.ToBase64String(Actual_Xmlhash1) == Convert.ToBase64String(Genrated_Xmlhash2))
{
Response.Write(" similar="">
}
else
{
throw new Exception("Files are different");
}
}
}

Sunday, July 14, 2013

get the current month and year in asp.net

Title:How to get current month and year in asp.net using c#.net

Description:
As per previous articles we have seen how get month and year using JQuery. Now i would like to explain and give the example on the same concept in c#.net.The C#.net provide the object "Date Time" which has some properties to get the retired data.As per our discussion i will use the two methods to get the current month and year.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int year = DateTime.Now.Year;
int month = DateTime.Now.Month;
int date = (DateTime.Now.Day)+2;
Response.Write(year.ToString()+ month.ToString()+date.ToString());
}
}

Wednesday, July 10, 2013

New features in Asp.net MVC 5

Erliar i have given Asp.net MVC4 related information with examples. Now the new version has came which is MVC 5 with new features.The below link will give the complete tutorial of MVC 5 with examples

Monday, July 1, 2013

Get dropdownlist selcted value in gridview in Asp.net

Title:
how Get Drop down List selected value  in grid view using c# in asp.net
Requirement: 
.Frame Work and Sql Server
Explanation:
Here i will show how to fire selected index event of drop down in grid view.When we work with drop down list in grid view ,Most  of  the confusion about how to get the selected value of DDL.By using this event(SelectedindexChanged) we can do it.
As per requirement have to display details of selected record details in report page.By using this ,will get Drop down selected value in grid view. In the above i have fetched the drop down list selected value which in grid view.

protected void ddlorders_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow GvOrderrow= (GridViewRow)ddlorders.NamingContainer;
DropDownList ddlOrdr_name= ((DropDownList)(GvOrderrow.FindControl(“ddlorders"))).SelectedValue;
if((ddlOrdr_name.SelectedValue.ToString()) =="")
{
Response.Write("No order Exist");
}
else
{
Respose.Redirect("Report.aspx?order='"+ CurrentOrdr+"'");
}


Tuesday, June 25, 2013

Transformations in WPF

It will use to change the position of a control in particular angle is called Transformation.WPF supports three types of
Transformations.
1.Rotate Transformation
2.Skew Transformation
3.Scale Transformation

Example:
Open WPF project
Replace grid with Canvas tag
Type as follows with in the Canvas
<Button.Render.Tranformation>
<Rotate Transform Angle="45"/>
//Skew:
<skew Transform angle x="30" ,angle y="30"/>
//Scale :
<Scale Transform scale x="2" scale y="2"/>

Wednesday, June 19, 2013

page error event in asp.net

This event can have error handling code using which user can get some info about the problem.Normally we will create page error event code by redirecting user with that page
protected void page_error(object seender,EventArgs e)
{
Response.Redirect("Error. Html");
}
protected void btn_clikc(object sender,EventArgs e)
{
int a=0,c=10;
int b=c/a;
Response.Write(b.Tostring());
}
Implemented using <custom errors> tag of web.config and also using application _error event of Global.aspx  file
Web.config:
<custom errors mode="on" DefaultRedirect="error.html"></custom errors>
In the same custom error a sub tag called error is present.In this tag we can specify particular error and redirecting
<appsettings>
<connectionStrings/>
<system.web>
<custom errors mode="ReadOnly" default Redirect="error.html"?
<error status code=404" redirect="nofile.html"/>
If user attempts to go for a file which is not present then nofile page will be displayed and for any other if goes to error page.Here we should notice "both files are created by user"

Saturday, June 8, 2013

Jquery highlight Gridview selected rows in asp.net

Title: How to highlight grid view rows using jquery in asp.net

Description:
using client script we can make lot functionality on design side.Now i would like explain how to use jquery on data controls in asp.net .Whenever we have to select specified rows with particular style on client side ,the jquery can solve this task

Example:
In previous articles we have seen Bind Data to Grid view,Edit,Delete,Update in Grid view in asp.net,Import Excel to Grid view asp net.Here i will show how to Highlight grid view selected rows.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Gridview selected Row highlight using jquery</title>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=GVdynamic.UniqueID%> tr").click(function () {
$(this).css("font-weight", "bold");
$(this).css("background-color", "SkyBlue");
$(this).css("border", "2px solid Green");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GVdynamic" runat="server" AutoGenerateColumns="False"
DataSourceID="sySql">
<Columns>
<asp:BoundField DataField="DyOrderID" HeaderText="DyOrderID" />
<asp:BoundField DataField="DyOrderName" HeaderText="DyOrderName" />
<asp:BoundField DataField="DyPhone" HeaderText="Phone" />
<asp:BoundField DataField="DyAddress" HeaderText="DyAddress" />
<asp:BoundField DataField="DyAmount" HeaderText="DyAmount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dySql" runat="server"
    ConnectionString="<%$ ConnectionStrings:Connection %>"
    SelectCommand="SELECT * FROM [dyOrders]"></asp:SqlDataSource>
</form>
</body>
</html>

Friday, May 17, 2013

Gridview inside gridview || Nested gridview in Asp.net

Title:How to use grid view inside grid view in asp.net using c#.net

Description:
Earlier we have seen how to Export grid view data to PDF,Bind data to grid view in asp.net.Here i will given an example for how to develop the nested grid view in asp.net.In this example the binding has done while page load event then the child grid view will populate on row data bound event.
Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Gridview inside gridview or Nested GridView in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvParentOrderReport" runat="server" OnRowDataBound="GvOrderReport_RowDataBound"
AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="OrderId"
GridLines="Horizontal">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Orderid" HeaderText="OrderId">
</asp:BoundField>
<asp:BoundField DataField="OrderName" HeaderText="OrderName" >
</asp:BoundField>
<asp:BoundField DataField="Phone" HeaderText="Phone" >
</asp:BoundField>
<asp:BoundField DataField="Address" HeaderText="Address" >
</asp:BoundField>
<asp:BoundField DataField="Amount" HeaderText="Amount" >
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td>
<asp:GridView ID="GvChildOrderNested" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="OrderId" HeaderText="OrderID"/>
<asp:BoundField DataField="OrderName" HeaderText="OrderName"/>
<asp:BoundField DataField="Phone" HeaderText="Phone"/>
<asp:BoundField DataField="Address" HeaderText="Address"/>
<asp:BoundField DataField="Amount" HeaderText="Amount"/>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>

using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _GridviewInsideGridview : System.Web.UI.Page
{
SqlConnection mcon = new SqlConnection("Data Source=Bhaskar\sqlexpress;Initial Catalog=Test;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
mcon.Open();
SqlCommand Parentcmd = new SqlCommand("select * from orders", mcon);
SqlDataAdapter Parentda = new SqlDataAdapter(Parentcmd);
DataSet Parentds = new DataSet();
Parentda.Fill(Parentds);
mcon.Close();
GvParentOrderReport.DataSource = Parentds;
GvParentOrderReport.DataBind();
}
}
     
protected void GvOrderReport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
mcon.Open();
GridView GvChildOrderNested = (GridView)e.Row.FindControl("GvChildOrderNested");
SqlCommand Childcmd = new SqlCommand("select * from orders", mcon);
SqlDataAdapter Childda = new SqlDataAdapter(Childcmd);
DataSet Childds = new DataSet();
Childda.Fill(Childds);
mcon.Close();
GvChildOrderNested.DataSource = Childds;
GvChildOrderNested.DataBind();
}
}
}

Wednesday, May 15, 2013

How to bind data to gridview with jquery in asp.net

In previous articles i have given Cascading dropdownlist using jquery .In this post i would like to explain how to bind data to gridview using Jquery. Here we can observe the page method calling using jquery post method
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind data to grid using jquery in asp.net</title>
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JqueryBindGrid.aspx/BindOrderDataToGrid",
data: "{}",
dataType: "json",
success: function (resData) {
    for (var i = 0; i < resData.d.length; i++) {
        $("#GvOrderDetails").append("<tr><td>" + resData.d[i].OrderId + "</td><td>" + resData.d[i].OrderName + "</td><td>" + resData.d[i].Phone + "</td><td>" + data.d[i].Address + "</td><td>" + resData.d[i].Amount + "</td></tr>");
}
},
error: function (result) {
alert("Exception");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GvOrderDetails" runat="server">
</asp:GridView>
</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.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Services;

public partial class JqueryBindGrid : System.Web.UI.Page
{
  
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable GVHeaderdt = new DataTable();
GVHeaderdt.Columns.Add("OrderId");
GVHeaderdt.Columns.Add("OrderName");
GVHeaderdt.Columns.Add("Phone");
GVHeaderdt.Columns.Add("Address");
GVHeaderdt.Columns.Add("Amount");
GVHeaderdt.Rows.Add();
GvOrderDetails.DataSource = GVHeaderdt;
GvOrderDetails.DataBind();
      
}
}
public class OrderReportDetails
{
public int OrderId { get; set; }
public string OderName { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Amount { get; set; }
}
[WebMethod]
public static OrderReportDetails[] BindOrderDataToGrid()
{
DataTable resDt = new DataTable();
List ORdetails = new List();
SqlConnection Dbcon = new SqlConnection(ConfigurationManager.AppSettings["DbOrdrCon"].ToString());
SqlCommand cmd = new SqlCommand("select * from Orders", Dbcon);
Dbcon.Open();
SqlDataAdapter Orda = new SqlDataAdapter(cmd);
Orda.Fill(resDt);
foreach (DataRow Ordt in resDt.Rows)
{
    OrderReportDetails OrderDetails = new OrderReportDetails();
    OrderDetails.OrderId = int.Parse(Ordt["OrderId"].ToString());
    OrderDetails.OderName = Ordt["OrderName"].ToString();
    OrderDetails.Phone = Ordt["Phone"].ToString();
    OrderDetails.Address = Ordt["Address"].ToString();
    OrderDetails.Amount = Ordt["Amount"].ToString();
    ORdetails.Add(OrderDetails);
}
Dbcon.Close();
return ORdetails.ToArray();
}
  
}

Tuesday, May 14, 2013

how to bind arraylist to gridview in asp.net

In previous articles we have seen how to bind the data to grid view, Bind data to dropdownlist,Bind data to dropdownlist in gridview,Export gridview to PDF.Here i would like to explain how to bind arraylist data to Grid view in asp.net.In the below i have used static array list for binding
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ArrayListToGridview.aspx.cs" Inherits="_ArrayListToGridview" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Bind ArrayList to Gridview</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvBindArrayList" runat="server"
AutoGenerateColumns="False" >
</asp:Gridview>
</form>
</body>
</html>

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

public partial class _ArrayListToGridview : System.Web.UI.Page
{
protected void Page_Load(Object Sender, EventArgs E)
{
if (!IsPostBack) {
ArrayList Booknames = new ArrayList();
Booknames.Add ("Asp.net");
Booknames.Add ("C#.net");
Booknames.Add ("SharePoint");
Booknames.Add ("SqlServer");
Booknames.Add ("Jquery");
Booknames.Add ("Asp.netMVC");
GvBindArrayList.DataSource = Booknames;
GvBindArrayList.DataBind();
}
}
}

Monday, May 13, 2013

jquery redirect to another page in asp.net

Title:How to redirect the from one page to other page in asp.net using Jquery

Description:
Basically the scripting language are used to perform dynamic data processing on client side.It will be improve the performance of application
Example:
In previous examples i have given Validate dropdownlist using Jquery,JqueryUI Autocomplete textbox,Jquery Modal popup for mail in asp.net,Jquery Get next/previous month of year.Here i would like explain how to redirect to other page when click on the button in Asp.net using jquery. We can use location method in two ways as you can see in the script
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnRedirect').click(function () {
window.location.href = 'About.aspx';
// or you can use
// location.href = 'About.aspx';
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnRedirect" runat="server" Text="Redirect" />
</form>
</body>
</html>

Sunday, May 12, 2013

how to export gridview to csv file in asp.net

Title: How to export grid view data to CSV or Text file in asp.net using c#.net

Description:
As per previous articles we have seen how to Bind CSV data to Grid view in asp.net,Export Grid view Data to Word Document,Export Grid view data to PDF document,Import XML data to GridView in Asp.net .Here i would like explain about how to export grid view data to CSV file in asp.net.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Export2CSV.aspx.cs" Inherits="Export2CSV" EnableEventValidation="false" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GvOrderDetails" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
<asp:Button ID="btnExportCSV" runat="server" Text="Gridview To CSV" onclick="btnExportCSV_Click" />
<div>
</div>
</form>
</body>
</html>
Code behind:In the below Grid view data bind has done while page loading.when we fire click event the data colud be export to CSV file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public partial class Export2CSV : System.Web.UI.Page
{
SqlConnection Econ = new SqlConnection(ConfigurationManager.ConnectionStrings["Exportconn"].ToString());
DataSet ds = new DataSet();
  
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlCommand cmd = new SqlCommand("select * from orders", Econ);
SqlDataAdapter Gda = new SqlDataAdapter(cmd);
Gda.Fill(ds);
GvOrderDetails.DataSource = ds;
GvOrderDetails.DataBind();
}
}

protected void btnExportCSV_Click(object sender, EventArgs e)
{
     
SqlDataAdapter Cda = new SqlDataAdapter("SELECT* FROM Orders",Econ);
DataTable Gdt = new DataTable();
Cda.Fill(ds);
    //Bind data to Data table
Gdt = ds.Tables[0];
StreamWriter Exportsw = new StreamWriter("E:\\OrderCSVReport.csv", false);
int CSVCount = Gdt.Columns.Count;
for (int i = 0; i < CSVCount; i++)
{
Exportsw.Write(Gdt.Columns[i]);
if (i < CSVCount - 1)
{
Exportsw.Write(",");
}
}
Exportsw.Write(Environment.NewLine);

foreach (DataRow Gdr in Gdt.Rows)
{
for (int i = 0; i < CSVCount; i++)
{
if (!Convert.IsDBNull(Gdr[i]))
{
Exportsw.Write(Gdr[i].ToString());
}
if (i < CSVCount - 1)
{
Exportsw.Write(",");
}
}
Exportsw.Write(Environment.NewLine);
}
Exportsw.Close();
}
}
}

Wednesday, May 8, 2013

cascading dropdownlists in asp.net MVC4

Title:
Cascading DropDownList in Asp.net MVC

Description:
AS we discussed in about cascading drop down in asp.net ,this articles will also describe the same functionality using model view controller frame work.Before going to read this article ,we should have some basic knowledge on Jquery and MVC patters.

Example:
What we have discussed in previous articles is cascading dropdownlist in asp.net,Required Validations Asp.net MVC4 ,Bind data to dropdownlist in MVC,jquery reference mvc.Now i would like explain how to develop cascading dropdownlist in MVC4.For you need to do the step by step process as per below code

View:
@{
ViewBag.Title = "Cacading Dropdownlist in Asp.net MVC4";
}
@using (Html.BeginForm())
{
<fieldset>
<legend></legend>
@Html.Label("CodeBook")
@Html.DropDownList("CodeBook", ViewBag.CodeBookRes as SelectList, "Select a CodeBook", new { id = "CodeBook" })
@Html.Label("Versions")
<select id="Versions"  name="Versions"></select>
</fieldset>
}

@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
$(function () {
$('#CodeBook').change(function () {
$.getJSON('/Cascading/VersionResList/' + $('#CodeBook').val(), function (data) {
var Listitems = '<option>please Select CodeBook</option>';
$.each(data, function (i, Versions) {
Listitems += "<option value='" + Versions.Value + "'>" + Versions.Text + "</option>";
});
$('#Versions').html(Listitems);
});
});
});
</script>
MVC4CacadingController:
This controller has two methods one is return the list and other one return the JSON result.The json result will call when make selection of Book dropdown
using CascadingDropdownlistMVC4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CascadingDropdownlistMVC4.Controllers
{
public class CascadingController : Controller
{
//
// GET: /Cascading/
public ActionResult Index()
{
List CodeBooks = new List();
CodeBooks.Add(new SelectListItem { Text = "Asp.netMVC", Value = "Asp.netMVC" });
CodeBooks.Add(new SelectListItem { Text = "Sharepoint", Value = "Sharepoint" });
CodeBooks.Add(new SelectListItem { Text = "SqlServer", Value = "SqlServer" });
CodeBooks.Add(new SelectListItem { Text = "Asp.net", Value = "Asp.net" });
CodeBooks.Add(new SelectListItem { Text = "C#.net", Value = "C#.net" });
ViewBag.CodeBookRes = new SelectList(CodeBooks, "Value", "Text");
return View();
}

public JsonResult VersionResList(string Id)
{
var VersionRes = from vs in VersioList.GetVersion()
where vs.Book == Id
select vs;
return Json(new SelectList(VersionRes.ToArray(), "Book", "Version"), JsonRequestBehavior.AllowGet);
}
}
}
Set Proprties:In this class i have created variable and set the propeties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDropdownlistMVC4.Models
{
public class SetProperties
{
public string CodeBooks { get; set; }
public string Versions { get; set; }
}

public class VersionList
{
public string Book { get; set; }
public string Version { get; set; }

public static IQueryable GetVersion()
{
return new List
{
new VersionList { Book= "Asp.netMVC", Version= "MVC3" },
new VersionList { Book= "Asp.netMVC", Version= "MVC4" },
new VersionList { Book= "SqlServer", Version = "2008R2" },
new VersionList { Book= "SqlServer", Version = "2012" },
new VersionList { Book= "Sharepoint", Version= "2010" },
new VersionList { Book= "Sharepoint", Version = "2013" },
new VersionList { Book= "Asp.net", Version = "4.0" },
new VersionList { Book= "Asp.net", Version = "4.5" },
new VersionList { Book= "c#.net", Version = "4.0" },
new VersionList { Book= "C#.net", Version = "4.5" },
}.AsQueryable();
}
}
}

Monday, May 6, 2013

how to export gridview data to pdf in asp.net

Title: How to export grid view data to PDF in asp.net

Description:
Most the report are send to customers as in excel format.But some scenarios they might ask PDF format.

Example:
Earlier we learned how to export grid view data to word document,Import excel data to SQL Server.In this post i will show how to export grid view data to PDF file in asp.net.While exporting to pdf i have created a pdf document with desired size .Then conversion has done using HTML parser
Note:itextsharp tool has been used.so we need add those DLL into our application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportToPDF.aspx.cs" Inherits="_ExportToPDF" %>
<!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>Export Gridview To PDF documnet</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvExportDetails" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" EnableModelValidation="True"
>
<Columns>
<asp:BoundField DataField="ExportOrderID"
                 HeaderText="ExportOrderID" SortExpression="ExportOrderID"/>
<asp:BoundField DataField="ExportOrderName"
                HeaderText="ExportOrderName" SortExpression="ExportOrderName"/>
<asp:BoundField DataField="ExportPhone" HeaderText="ExportPhone" SortExpression="ExportPhone" />
<asp:BoundField DataField="ExportAddress" HeaderText="ExportAddress" SortExpression="ExportAddress" />
<asp:BoundField DataField="ExportAmount" HeaderText="ExportAmount" SortExpression="ExportAmount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
</div>
<asp:Button ID="btnExportOrdersToPdf" runat="server"
             OnClick="btnExportOrdersToPdf_Click"
             Text="OrderDetails to PDF" />
</form>
</body>
</html>
Code behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

public partial class _ExportToPDF : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnExportOrdersToPdf_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=OrderDetailsReport.pdf");
Response.Charset = string.Empty;
Response.ContentType = "application/vnd.pdf";
StringWriter swr = new StringWriter();
HtmlTextWriter hwr = new HtmlTextWriter(swr);
GvExportDetails.RenderControl(hwr);
StringReader srd = new StringReader(swr.ToString());
Document OrderDetialsReport = new Document(PageSize.A1, 12f, 12f, 12f, 10f);
HTMLWorker _htmlparser = new HTMLWorker(OrderDetialsReport);
PdfWriter.GetInstance(OrderDetialsReport, Response.OutputStream);
OrderDetialsReport.Open();
_htmlparser.Parse(srd);
OrderDetialsReport.Close();
Response.Write(OrderDetialsReport);
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
  
}
Note:Errors might be come like "registerforeventvalidation can only be called during render"

Sunday, May 5, 2013

Export gridview data to word document in asp.net

Title:How to export data from grid view to word document in asp.net using c#

Description:
As per previous articles we have learnt the reporting is the mandatory step for any web application.The data can be exported in different formats like PDF,Excel etc,Now i would like to explain on export data to word document from grid view

Example:
What we have read :
how to export grid view to excel,bind excel data to grid view in asp.net.Here this example will describe how to export Grid view data to word document in asp.net.

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvOrder" AllowSorting="True" AllowPaging="True" Runat="server" AutoGenerateEditButton="True" AutoGenerateDeleteButton="True"
AutoGenerateColumns="False" DataSourceID="OrdrDb">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"/>
<asp:BoundField DataField="OrderName" HeaderText="OrderName"/>
<asp:BoundField DataField="Phone" HeaderText="Phone"/>
<asp:BoundField DataField="Address" HeaderText="Address"/>
<asp:BoundField DataField="Amount" HeaderText="Amount"/>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="OrdrDb" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
<asp:Button ID="btnexportOrderstoWord" runat="server" Text="Button"
onclick="btnexportOrderstoWord_Click" />
</form>
</body>
</html>

Code behind:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class ExporttoWord : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnexportOrderstoWord_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=gvOrderToWord.doc");
Response.ContentType = "application/vnd.ms-word ";
StringWriter swr = new StringWriter();
HtmlTextWriter hwr = new HtmlTextWriter(swr);
gvOrder.AllowPaging = false;
gvOrder.DataBind();
gvOrder.RenderControl(hwr);
Response.Write(swr.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control GvOrder)
{
}
}
Note:While executing this class we may get this kind of error because of render control.please click here for solution "RegisterForEventValidation can only be called during Render"

Friday, May 3, 2013

RegisterForEventValidation can only be called during Render in asp.net

In previous post i have given how to Export Gridview data to excel in asp.net,Read data from excel file,Bind excel data to gridview,Export gridview data to word document.In this post i will explain how to resolve the RegisterForEventValidation error while generating reports from gridview.To resolve this kind of  error we need to render the controls then add the set the EnableEventValidation property to False at Page directive(you see the highlighted text).

Code behind:
This peace of code have to add in class.It will render the control to desired response while working with controls

public override void VerifyRenderingInServerForm(Control control)
{
}

HTML:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportToWord.aspx.cs" Inherits="ExportToWord" EnableEventValidation="false"
%>

Thursday, May 2, 2013

gridview paging and sorting without postback in asp.net


In previous articles we have seen Bind data to dropdownlist in gridview,edit,delete,update in grdivew.In this post i will show how to avoid the post back while doing the sorting and paging in gridview.For this we need the set the EnableSortingAndPagingCallbacks to true,then it can perform client side callbacks to fetch the data.If we are using Template field.This property can not support.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Gridview Paging and Sorting with out postback</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvSales" AllowSorting="True" Runat="server"
 EnableSortingAndPagingCallbacks="true" AllowPaging="true" 
AutoGenerateColumns="False" DataSourceID="SalesDb" 
       PageSize="4">
<Columns>
            <asp:BoundField DataField="SalesID" HeaderText="SalesID"
                 SortExpression="SalesID" />
             <asp:BoundField DataField="SalesPersonName" HeaderText="SalesPersonName"
                SortExpression="SalesPersonName" />
             <asp:BoundField DataField="SaleCity" HeaderText="SalesCity" SortExpression="SaleCity" />
             <asp:BoundField DataField="SalesAmt" HeaderText="Samount"
                 SortExpression="Samount" />
          </Columns>
       </asp:GridView>
<asp:SqlDataSource ID="SalesDb" runat="server"
            ConnectionString="<%$ ConnectionStrings:bhaskarConnectionString %>"
            SelectCommand="SELECT * FROM [Sales_Orders]"></asp:SqlDataSource>
 </div>
 </form>
</body>
</html>
Paging and sorting in Gridview

Tuesday, April 30, 2013

How to send a mail in asp.net

Title: How to send an email in asp.net using c#.net

Description:
In previous posts i have given send a mail with attachment in asp.net,Send mail using service,send a Email with html Format in Asp.Net.In the same way i just given an example on sending email concept in asp.net.The following example has two text boxes which are used to give the subject and name to mail message
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send a mail in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSub" runat="server"></asp:TextBox>
<asp:TextBox ID="txtbody" runat="server"></asp:TextBox>
<asp:Button ID="btnsendmail" runat="server" Text="Send" onclick="btnsendmail_Click" />
</form>
</body>
</html>
Codebehind:
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Mail.Net;

public partial class _sendmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsendmail_Click(object sender, EventArgs e)
{
try
{
SmtpClient SmtpmServer = new SmtpClient(SmtpserverName);
SmtpmServer.Credentials = new System.Net.NetworkCredential(Username, PWD);
MailMessage MlMsg = new MailMessage();
MlMsg.From = new MailAddress("bhaskar7698@gmail.com");
MlMsg.Body = txtbody.Text;;
MlMsg.IsBodyHtml = true;
MlMsg.To.Add(mulebhaskarareddy@gmail.com);
MlMsg.Subject = txtSub.Text;
SmtpmServer.Send(MlMsg);
Respose.Write("Mail sent successfully");
}
catch (Exception em)
{
Respose.Write(em.Message.Tostring());
}
}
}

Monday, April 29, 2013

Edit,delete,update records in gridview using sqldatasource in asp.net

Title: Edit Delete Update in Grid view in asp.net

Description:In previous post i have given how to edit,delete,update in grid view using row events,Bind data to grid view using SQL data source(here you can see how to use it).For this we need to set the  properties for grid view to enable the columns for db transaction.Might be get where the DML commands are executed?.The answer is the sqldatasource has properties to executes those commands when user perform those action on grid view

Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OrderGrid.aspx.cs" Inherits="OrderGrid" %>
<!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="GvOrder" AllowSorting="True" Runat="server"
AutoGenerateEditButton="True" AutoGenerateDeleteButton="True" AutoGenerateColumns="False" DataSourceID="OrdrDb">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"
SortExpression="OrderID" />
<asp:BoundField DataField="OrderName" HeaderText="OrderName"
SortExpression="OrderName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="Amount" HeaderText="Amount"
SortExpression="Amount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="OrdrDb" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]" UpdateCommand="UPDATE [Orders] SET [OrderName] = @OrderName, [Phone] = @Phone,
[Address] = @Address, [Amount] = @Amount WHERE [OrderID] = @OrderID" DeleteCommand="Delete [Orders] WHERE [OrderID] = @OrderID"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
Result:
Display Order table table using Data source:
Bind data to gridview
Update Records using edit operation in grid view





Saturday, April 27, 2013

delete all gridview rows using checkbox in asp.net

Title:
How to delete rows in grid view using check box in asp.net

Introduction:
Hi all,I think you have seen so many articles and websites on grid view functionalists.But why i have given again the same delete records in grid view?".This question should get every one when you reading the title.The answer is,I would like to share the code or logic what i have done earlier in easy manner.Let go to the our task.I hope the below explanation is useful for us.Thanks to reading..

Example:
Some previous articles
select the multiple rows of grid view,
Get the check box in grid view using Jquery.
In this post i will show how to delete the all rows from grid view using check box in grid view.The design page have the grid view layout with item templates and and check which is used to select the specified rows in grid view to make functionality better
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Delete All Rows in grid view with check box in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvOrder" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Order NO.">
<ItemTemplate>
<asp:Label ID="lb1OrderId" Text='<%#Eval("OrdrNo") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField><asp:TemplateField HeaderText="OrderName Name">
<ItemTemplate>
<%#Eval("Ordrname") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<%#Eval("Amtsal") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="btnchkall" runat="server" OnClick="btnchk_Click">Check All</asp:Button><asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click">Delete</asp:Button>
</form>
</body>
</html>
Code behind:
The connection string settings in the config file has been made as per in the below snippet.It contain server and data base name.Before going to add this code we have to create a connection to database in web.config file. Here my connection name is "OrderDetailsConnection".

<appSettings>
<connectionStrings>
<add key="OrderDetailsConnection" value="server=bhaskar/SQLEXPRESS;database=Order_Db;uid=bhaskar;password=br123;" />
</connectionStrings>
</appSettings>

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _GrdivewChkDelete : System.Web.UI.Page 
{
SqlConnection cn = new SqlConnection(ConfigurationSettings.AppSettings("OrderDetailsConnection");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindOrdrGrid();
}
private void BindOrdrGrid()
{
SqlDataAdapter OrdrAd = new SqlDataAdapter("Select * from Order",ocn);
DataSet Ordrds = new DataSet();
OrdrAd.Fill(Ordrds);
GvOrder.DataSource = Ordrds;
GvOrder.DataBind();
}
protected void btnchkall_Click(object sender, EventArgs e)
{
CheckBox rchk;
for (int i = 0; i < GvOrder.Rows.Count; i++)
{
rchk = ((CheckBox)(GvOrder.Rows[i].FindControl("orbrcb")));
if (orbrcb.Checked == false)
//Check all check box in gridview
orbrcb.Checked = true;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
CheckBox rchk;
String ordrId = String.Empty;
for (int i = 0; i < GvOrder.Rows.Count; i++)
{
rchk = ((CheckBox)(GvOrder.Rows[i].FindControl("orbrcb")));
if (orbrcb.Checked){//Get the Id from lable
ordrId +=((Label)(GvOrder.Rows[i].FindControl("lb1OrderId"))).Text + ",";
}
}//Get the Order_Id
ordrId = ordrId.Substring(0, ordrId.Length - 1);
cn.Open();
//Delete all grdivew records
SqlCommand cmd=new SqlCommand("delete from Order where Order_Id in("+ordrId.ToString()+")",cn);
cmd.ExecuteNonQuery();
BindOrdrGrid();
}
}
//In the above code i have used to delete the records using "IN"  in sql command.By using this we can delete the all records with in the list.Keep coming to get latest updates 

Friday, April 26, 2013

Asp.net validation controls

Title:How to use validation control in asp.net

Description:
Normally in web application, validation are perform using java script. We must write JS and perform validations.If validations are successful then we redirect the user to sever and if validation fails then we display error to user to perform all these with java script. It is complex and also time consuming.In previous articles i explained how to pass server side variable to client side in asp.net,Validate drop down list in java script,How to validate text box in JQuery

Asp.net developers are provided with validation controls which enable user to perform validation just like server side controls.These validation controls render Jquery to the client or browser like this we can have rapid application development for validation and also we can reduce the Complexity of writing java script code validation controls of asp.net target clients as automatic which means based on browser validation are perform

The fallowing validation controls are supported by asp.net
1.Required Field validator
2.Range validator
3.Compare validator
4.Regular expression validator
5.Custom validator
6.Dynamic validator
7.validation summary

The most common property for validation controls:
Controltovalidate:web control id
Error message =message
setFoucsError=true/false
validation Group :makes the control part of separate validation group
Display:static(default)/dynamic/none
i.static :Initially place for displaying error will be reserved.When error occurs it will be visible otherwise it will be hidden
ii.Dynamic:No place in the form will be reserved initially only on error dynamically the message will be shown
iii.none:will not display the error message only

Required field validator:

Used to check null values and it is the only control that checks null values .Remaining validation controls doesn't perform any validation if null values are entered.IN the below example have used this validation for Textbox(txtOrder) which is used to give the Order value.
<asp:requiredfieldvalidator controltovalidate="txtOrder" display="dynamic" errormessage="Enter Order Details" id="RfOrder" runat="server">* 
</asp:requiredfieldvalidator>

Range validator:

To check for range of values.Useful for numeric and date format of data Additional properties Minimum value :1
maximum Value :1000

<asp:textbox id=" runat="server" txtage=""> <asp:RangeValidator id="RvAge" runat="server" ControlToValidate="txtage" 
 MaximumValue="16" 
 MinimumValue="24" 
 Type="Integer" 
 ErrorMessage="Enter valid age" Display="Dynamic">*</asp:RangeValidator>
Can one control have multiple validation controls? the answers is yes
we can use one validation control validate single controls only

Compare validator:

With compare validation we can perform 3 types of validation all will be based on comparison
1.Control with another control
2.control with value
3.control with data type

 UserName<asp:textbox id="txtuser1" runat="server"/>
 Reenter UserName: <asp:textbox id="txtuser2" runat="server"/>

<asp:CompareValidator ControlToValidate="txtuser1" ControlToCompare="txtuser2" Operator="Equals" ErrorMessage="Please enter valid user name" Display="dynamic">*</asp:CompareValidator>

validation summary control:

Used to report errors as a summary i:e display all control errors.error message display throw summary control.It has two properties
i)show summary :true/false
ii)show messageBox =true/false
when display is set to none then validation control will not display error in its place instead if displays error in summary control .

Regular expression validator:

Using they control we can specify on expression and ask validator to match the expression with control.Previously i have given to validate email using regular expression in asp.net.

Custom validator:

In previous post i have given example on how to use custom validator in asp.net.For complete details click here

Thursday, April 25, 2013

Bind data to datalist in asp.net

Title:How to bind data to data list in asp.net using c#.net

Description:
In previous post we have seen bind data to grid view,bind xml data to grid view in asp.net.In this post i will show how to bind the data to data list using SQL Data source in asp.net.Here we don't need write the code to get the data for data list
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" Font-Size="10pt" Width="350px" HeaderStyle-BackColor="ActiveBorder"
 AlternatingItemStyle-BackColor="Aqua" DataSourceID="SqlDataSource1">
<HeaderTemplate>
Order Details
</HeaderTemplate>
<ItemTemplate>
OrderID: &nbsp;<asp:Label ID="OrderIDLabel" runat="server" Text='<%# Eval("OrderID") %>' />
OrderName:
<asp:Label ID="OrderNameLabel" runat="server" Text='<%# Eval("OrderName") %>' />
Phone:
<asp:Label ID="PhoneLabel" runat="server" Text='<%# Eval("Phone") %>' />
Address:
<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />
Amount:
<asp:Label ID="AmountLabel" runat="server" Text='<%# Eval("Amount") %>' />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
1.Select data source for data list using options
Design mode ->Data list Tasks->choose new data source
2.Select the SQL Data Source->click next
3.Create new connection wizard will open.In this we have make select the new connection button.
4.Select the data base which you want to use
5.click on next then get wizard to configure the data using query.
6.click finish

Tuesday, April 23, 2013

How to bind data to dropdownlist with arrarylist in asp.net


In previous post we have discussed on how to bind the Data in Gridview,Disable dropdownlist .In this post i will show how to bind data to dropdownlist using array list in asp.net.Here i will populate drop down for city names.
<html>
<head>
</head>
<body>
<form runat=server>
<asp:DropDownList id="ddlcity" runat="server" />
</form>
</body>
</html>
We have to used ispostback to avoid the populating drop down while every time loading the page

protected void Page_Load(Object Sender, EventArgs E) 
{
if (!IsPostBack) {
ArrayList citynames = new ArrayList();
citynames.Add ("NewYork");
citynames.Add ("Hyderabad");
citynames.Add ("Bombay");
ddlcity.DataSource = citynames;
ddlcity.DataBind();
}
}

Monday, April 22, 2013

how to get selected items from checkboxlist in asp.net c#


In previous post i have given how to get the id of checkbox using jqury ,check all checkbox in gridview.In this post i will show how to get the selected values of check box list in asp.net.I below piece of code i have looping thorough the check box list items on button click event .Then the resultant value has assigned to string
<html>
<head>
</head>
<body>
<form>
<asp:CheckBoxList ID="ChkOrdrList" runat="server">
<asp:ListItem>COmputers</asp:ListItem>
<asp:ListItem>Books</asp:ListItem>
<asp:ListItem>Laptop</asp:ListItem>
<asp:ListItem>Ipad</asp:ListItem>
</asp:CheckBoxList>
<div>   
<asp:Button ID="btngetOrdr" Text="Ok" OnClick="btlgetOrder_Click" runat="server" />
</div>
<asp:TextBox ID="txtOrdername" runat="server" />
</form>
</body>
</html>

public void btlgetOrder_Click(object Source, EventArgs e)
{
String strOrdr = "Checkboxlist selected Item is:";
for (int i = 0; i < ChkOrdrList.Items.Count; i++)
{
if (ChkOrdrList.Items[i].Selected)
{
strOrdr = strOrdr +","+ ChkOrdrList.Items[i].Text;
}
}
txtOrdername.Text = strOrdr;
}

how to create usercontrol with user defined properties in asp.net

In previous posts i have given examples on how to convert string to data table in asp.net,Gridview Examples,Add colums dynamically to gridview.Her i will show how to develop a scrolling label control with text,color,font  properties using csharp.The timers are used to get the time inteval of process
Place label control
Place Timer Control with enabled =true
Place one more timer with enabled =false

Code fro timer_TickEvent(--)
{
lblname.Top=lblname.Top-5;
if(lblname.Top<0)
{
Timer1.Enable=false;
Timer2.Enable=True;
}
}
Code for time2_tick event(...)
{
lblname.Top=lblname.Top+5;
if(lblname.Top>250)
{
Timer1.Enable=false;
Timer2.Enable=True;
}
}
//Code in General Declaration
//create properties
Publlic string Ltext
{
set {lblname.Text=value;}
get{return lblname.Texte;}
}

Publlic string Lbcolor
{
set {lblname.BackColor=value;}
get{return lblname.BackColor;}
}

Publlic string Lfont
{
set {lblname.Font=value;}
get{return lblname.Font;}

}
Publlic int Lspeed
{
set {timer1.interval=value;
timer1.interval=value;
}
get{return timer1.Interval;}

}
Build the project
note:Scrolling lable.dll is created under d:\myprojects\scrolling label \bin\debug folder
Open page and drag scrolling.dll into my controls tab of toolbox.Then user control slable has been added to tool box

Tuesday, April 16, 2013

GridView TemplateField in asp.net || how to bind the Data in Gridview TemplateField in asp.net


Inprevious posts i have given examples on how to export data from gridview to excel,Bind dropdown in gridview .Here i will explain the gridview template fields. Template field is used for complex content and it is unlimited and also can be used for any type of presentation.It is both attribute based and content based for producing output.It's content is defined using templates.A template is an area where we can present any type of data .Template fields has no attribute for retrieving data from data objects and it uses asp.net data binding expressions to retrieve data and support data binding.The following syntax and statement are used for writing data bind expressions
<%# data bind expression #>
<%# Eval("filedname") #> (2.0)
<%# Bind("filedname") #>
<%# DataBinder.Eval(container.DataItem,"filedname")%>
The last method is the older asp.net method

Eval gets data from data object and bind gets data from data object like eval but also sends data back to data object for changes,It is conditional
Note:db expression can be written separately inside templates and also along with properties of controls when used.Along with properties.we must enclose them in single quotes
<asp TextBox Text='<%#Eval("job_id")%>'> </asp:Texbox>

Monday, April 15, 2013

Collection initializer in c sharp


Collection initializers are extension of object initializers.It look like an array.To create a collection initializers ,Auto-implemented properties are required.To work with this,a generic data type called as list is required.Generic data type holds any type of data. These are similar to c++ templates and will be indicated with <>

Example:
Code in General declaration
class result
{
public int marks {set; get;}
public string sname {set; get;}
public int id {set; get;}
}
Code for btn click
{
list<result> rs= new list<result>
{
new result{marks=100,sname="siva",id=1}
new result{marks=100,id=2}
}
foreach(result r,int rs)
Messagebox.Show(r1.marks+" "+r1.sname+" "+r1.id);
}
In the above i have taken one button to done this example

Saturday, April 13, 2013

object initializer in c sharp

In this post  i would like to give an example on object initializers in c#.net.
1.Object initializers are used to initialize the instance variables automatically
2.These are bit similar to constructions syntaxically
obs:
if the class name is test
Test t=new test(101,"bhaskar") is called as constructor
Test t=new test{eno=101,ename="bhaskar"} is called as object initializers
In the above syntax eno and ename are two implemented properties
3.The main objective of object initializer is to save no of lines  in the source code

Example:
place a button on the form
Cod in GD
class emp
{
public int eno {set;get}
public int sal {set;get}
public string name {set;get}
}
Code for button click event
{
emp e1= new emp{eno=101,ename="bhaskar",sal=5000};
MessageBox.Show(e1.no+""+e1.name+""+e1.sal);

Monday, April 8, 2013

Automatic password change in SharePoint 2013

Share Point 2013 provides the automatic password change feature which will use to update the password
for managed accounts with out manual changes.By using APC we can modify the pass on scheduled time,Quickly reset the all passwords ,Get the expiration time of the passwords etc.
For complete description please click link here 

Sunday, April 7, 2013

new and update for share point 2013


The below are the updated and new things have been added  to Share Point 2013 by march.
New:
1. XLIFF interchange file format .click here  for more
2.Customize  page layouts for a catalog-based site . For Brief Description
3.BCS connection objects
Updated:
1.BCS REST API reference
2.Create external event receivers
3.e Discovery 
4.eDiscovery and compliance
5.design packages 

Download Visual studio 2012 Update 2 (VS2012.2)


Visual Studio 2012 update has been done by last week .The following are the new features that have been included in this update.
1.Web access to  the test case management tools in Team Foundation Server.
2.Windows Store development.
3.Line-of-business development.
For complete details of update click here
Download VS2012 update 2(VS2012.2)

Monday, March 25, 2013

How to insert the multiple values using LINQ in asp.net


In previous posts we have seen  how to insert the data into data base using sql server in asp.net with c sharp.  Now  i will given an example to insert the multiple fields  using LINQ in asp.net.Here i have used USING  to maintain the scope of the patientinfo.
using (PatientInfo pf = new PatientInfo())
{
t_patientDetails objpd =new t_patientDetails()
objpd.Name = Name;
objpd.Mobile = Mobile;
objpd.OPNO = OPNO;
objpd.Date = DateTime.Now;
pf.t_patientDetails.InsertOnSubmit(objpd);
pf.SubmitChanges();
}

Monday, February 18, 2013

How to get the information of database in sqlserver

The sql server provides a procedure to get the information of desired data base .i;e SP_HELPDB.
In the below picture we can see the data and log information of the database.Here i have used query to get the data of existing database.
sp_helpdb 'Test krishna'

The result will show the size,administrator  and  status of the DB
 

Wednesday, January 9, 2013

Disable dropdown list using radio button in asp.net using c#.net

In previous post we have seen how to disable the drop down list using other dropdown list.In the below we will use radio button to disable the drop down list in asp.net using c#.net.For this we have to use radiobutton checked change event
Code behind:
protected void rbcheck_CheckedChanged(object sender, EventArgs e)
{
ddltest.Enabled = false;
}

Aspx:
 <asp:RadioButton ID="rbcheck" runat="server"
 oncheckedchanged="rbcheck_CheckedChanged"  AutoPostBack="true"/>
<asp:DropDownList ID="ddltest" runat="server"
 AutoPostBack="True">
<asp:ListItem>Please select</asp:ListItem>
</asp:DropDownList>

Tuesday, January 8, 2013

Disable/enable Dropdownlist in asp.net using c#.net

In this post i will show how to disable a drop down in asp.net using c#.net.Here i have used two drop down lists to perform this task. Whenever  the first drop down  selected then another drop down will be disabled
Aspx:
<asp:DropDownList ID="ddloption" runat="server" onselectedindexchanged="ddloption_SelectedIndexChanged" 
       AutoPostBack="True">
<asp:ListItem>Please select</asp:ListItem>
<asp:ListItem>Hyderabad</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlcode" runat="server" 
AutoPostBack="True">
<asp:ListItem>Please select</asp:ListItem>
</asp:DropDownList>
Code :
protected void ddloption_SelectedIndexChanged(object sender, EventArgs e)
{
ddlcode.Enabled = false;
}
The above code is for drop down selected index event for first drop down list

Monday, January 7, 2013

Get the dropdown selectedIndex in asp.net using c#.net

In previous post we have seen how to get the drop down selected value.In this post i will show how to get the selected index value in asp.int using c#.net.Here i have used one drop down list and label to display index value.

Code:
protected void dtest_SelectedIndexChanged(object sender, EventArgs e)
{
 lbly.Text = dtest.SelectedIndex.ToString();
}
aspx:
<asp:DropDownList ID="dtest" runat="server" onselectedindexchanged="dtest_SelectedIndexChanged"
       AutoPostBack="True">
<asp:ListItem>Please select</asp:ListItem>
<asp:ListItem>Hyderabad</asp:ListItem>
<asp:ListItem>Chennai</asp:ListItem>
<asp:ListItem>Bombay</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lbly" runat="server" Text="Label"></asp:Label>


Get the dropdown selected value in asp.net using c#.net

Title:
How to get the drop down list selected value in asp.net using c#

Description:
The drop down list will display the list of items and each list of item is selectable.The best thing  of this control is ,we can bind static data or dynamic data which is to be done by using data binding concept.Now we know this control can support data binding

Example:
Some recent posts on drop down list selected value ,Jquery Drop down list validation .Now i would like to give an example on  how to get the drop down selected value in asp.net using c#.Before going to start ,we have to add one drop down list with label control which will be used to  display the drop down selected value .
Note:One more thing we need to remember i:e auto post back property set to true.If you want to see the properties of web control ,focus on control and click on F4

Aspx page:
<asp:DropDownList class="HTML" id="ddlcitytest" name="code" onselectedindexchanged="ddlcitytest_SelectedIndexChanged" runat="server"AutoPostBack="True">
<asp:ListItem>Please select</asp:ListItem>
<asp:ListItem>Hyderabad</asp:ListItem>
<asp:ListItem>Chennai</asp:ListItem>
<asp:ListItem>Bombay</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lblcity" runat="server" Text="Label"></asp:Label>

codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlcitytest_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the selected value
lblcity.Text = ddlcitytest.SelectedValue.ToString();
}
}
In the above code the selected value has been assigned to label for display purpose.


Thursday, January 3, 2013

How to disassemble the dll in .net

It will need when we have to change any modifications to precomplied dll.There is no straight way to make changes to dll.For this i have used to ".net Reflector" which has to be downloaded then check which class file has to be changed.
DLL into sourcecode
Finally make change in source code files and create compiled DLL

Wednesday, January 2, 2013

How set default page in iis for Asp.net application


There are two ways to be set default page for application.One way is adding the default document to configuration file(web.config).Other way is directly set the default document in IIS
<system.webServer>
    <defaultDocument>
        <files>
            <add value="~/OrdsrHome.aspx"/>
        </files>
    </defaultDocument>
</system.webServer>
Configure in IIS :
Click on application -->go to Features view then do the below process as per screen shots



The default Page has been set to application as you can see in the above image
 

Bel