Showing posts with label Grid view. Show all posts
Showing posts with label Grid view. Show all posts

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+"'");
}


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();
}
}
}

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"

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 

Monday, October 29, 2012

Dynamically add columns to GridView in asp.net using C#.net

Title:How to create dynamic columns in grid view in asp.net using c#.net

Description:
Up to now we have gone through the data binding concepts like bind data to drop down list in grid view and how to use the link button in grid view.Here i would like to explain how to do customized grid view using c#.net.t.For this the i have created a data table which has three columns and assign the list data to data table using iterations.The resultant grid view can see in the below image

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add rows Dynamically to grdivew</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:gridview autogeneratecolumns="False" id="DynamicColAddGrid" runat="server">
</asp:gridview>
</div>
</form>
</body>
</html>


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

public partial class _DynamicCol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> li = new List<string>();
li.Add("Bhaskar");
li.Add("Siva");
li.Add("Ram");
li.Add("Venky");
li.Add("Hari");
li.Add("Aru");
li.Add("Srinu");
li.Add("anil");
li.Add("sri");
li.Add("john");
DataTable ddt = new DataTable();
DataRow darow;
DataColumn dc = new DataColumn("Id", typeof(string));
DataColumn dc1 = new DataColumn("Name", typeof(string));
DataColumn dc2 = new DataColumn("FullName", typeof(string));
ddt.Columns.Add(dc);
ddt.Columns.Add(dc1);
ddt.Columns.Add(dc2);
int ditem = 0;
while (ditem < 8)
{
darow = ddt.NewRow();
ddt.Rows.Add(darow);
ddt.Rows[ditem][dc] = ditem.ToString();
ddt.Rows[ditem][dc1] = li[ditem].ToString();
ddt.Rows[ditem][dc2] = li[ditem].ToString();
ditem++;
}    
DynamicColAddGrid.DataSource = ddt;
DynamicColAddGrid.DataBind();  
}
}
Result:

Sunday, July 1, 2012

How to Bind data to gridview in asp.net

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

Description:
This is the basic concept of the data binding to data source controls in asp.net.Now i would like to explain and given example on bind data to drop down list in grid view,In this post i will explain how to bind the data to grid view example in asp.net.Here the stored procedure has been used to get the data from sql database.In the same way we can see how to call a stored procedure in this example

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Bind data to gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grvdoc" AllowSorting="True" Runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

Code Behind:

protected void Page_Load(Object Sender, EventArgs E) 
{
SqlConnection con=new SqlConnection("Data Source=Test;Initial Catalog=binddata;Integrated Security=true")
SqlCommand cmd = new SqlCommand("fiilldocgridview", con);
cmd.CommandType = CommandType.StoredProcedure;con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);DataSet ds = new DataSet();
try
{
da = new SqlDataAdapter(cmd);
da.Fill(ds, "DoctorsTable");
grvdoc.DataSource = ds;
grvdoc.DataBind();
}
catch
{
throw;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
}
filldocgridview Stored Procedure:

CREATE PROCEDURE [dbo].[fiilldocgridview]
AS
SELECT * FROM  binddata

Friday, May 25, 2012

BInd data to dropdownlist in gridview in asp.net

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

Description:
In previous posts i explained Asp.net bind data to grid view,bind data to dropdownlist,Bind drop down in MVC4.Bind grid view using LINQ. Here i will show how to binding the data to Drop down List inside of Grid View.Here the dropdownlist has place inside of grid view template Field .You can observe here i will bind data to both drop down and grid view While loading page.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Bind data to Dropdownlist in gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvSalesData" AllowSorting="True" Runat="server"
AllowPaging="true" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="SalesID">
 <ItemTemplate>
 <%#Eval("SID")  %>
 </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SalesPName">
 <ItemTemplate>
<%#Eval("SalesPersonName")  %>
</ItemTemplate>
</asp:TemplateField>
 <asp:TemplateField HeaderText="Samount">
 <ItemTemplate>
<%#Eval("Samt")  %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SalesCity">
<ItemTemplate>
<asp:DropDownList ID="ddl_city" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
 </form>
</body>
</html>
Code behind:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Dropdowningridview : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["bhaskarconnection"].Tostring());

protected void Page_Load(object sender, EventArgs e)
{
If(!page.IsPostBack)
{
//Bind data to gridview
BindOrdrGrid();
//Bind data to Dropdown in gridview
BindDropdownGrid();
}
private void BindOrdrGrid()
{
 SqlDataAdapter Ordr_ad = new SqlDataAdapter("select * from Order_details", cn);
 DataSet Ordr_ds = new DataSet();
 Ordr_adp.Fill(Ordr_ds, "Order_details");
 GvSalesData.DataSource = Ordr_ds;
 GvSalesData.DataBind(); 
}
private void BindDropdownGrid()
{
cn.Open();
SqlDataAdapter Ddl_ad = new SqlDataAdapter("select * from order_city", cn);
DataSet Ddl_ds = new DataSet();
ad.Fill(Ddl_ds, "order_city");
foreach (GridViewRow row in GvSalesData.Rows)
{
DropDownList _ddlcity = (DropDownList)(GvSalesData.Rows[row.RowIndex].Cells[4].FindControl("ddl_city"));
_ddlcity.DataSource = Ddl_ds;
_ddlcity.DataValueField = "CID";
_ddlcity.DataTextField = "City_name";
_ddlcity.DataBind();
}
}

Wednesday, March 28, 2012

Datatable to Gridview in asp.net

Title: How to bind the data to grid view using data table in asp.net c#.net

Description:
Here i will show how to transfer the data the from data table to Grid view .For this i have generated custom data table " dtOrders" and add desired columns to it.Then i created a object to add the row data into data table and expression property is used to get the desirable format of data.

Example:
DataTable dtOrder = new DataTable();
dtOrder.Columns.Add("OrderId"); 
dtOrder.Columns.Add("Name");  
dtOrder.Columns.Add("Quantity");  
dtOrder.Rows.Add(new Object[] { "12", "pharmacy", "2000" });
dtOrder.Columns[3].Expression = string.Format("{0},{1},{2}", "OrderId", "Name", "Quantity"); 
gvOrders.DataSource = dtOrders;    
gvOrders.DataBind();

Friday, December 9, 2011

GridView Sorting and Paging in Asp.net

Title : Paging and sorting in grid view in asp.net using c#

Description:
Recently While working with the grid view sorting ,i have noticed the the functionality and do the example on in grid view using c sharp.Here i will shown how sort the data and pagination in grid view.The below specified code will make sorting when clicking on  grid view header .So first we have to do some properties set up i:e
Allow sorting-->True:-column headings will be provided with hyperlinks[link button]
Code behind:
//pageload
if(page.ispostback==false)
{
//ordinary request information will be displayed sorted based on the empname
Sqlconnection con=New Sqlconnection("userid=sa";password=;databse=emp");

SqlDataadaptor da=New SqlDataadapator("select*from Employee Orderby empname",con);

//orderby is used to retrieve records in sorted order
Dataset ds=New Dataset();

da.fill(ds,"Employee");

Gvemp.Datasource=ds.Table["Employee"];
Gvemp.DataBind();
}
Providing Logic For Grid view Event:-
When user clicks on the column header of grid view post back takes place,sorting event procedure of grid view will be executed.This Event procedure will be provided column name
protected void Gridview-sorting(Object sender,Event Args e)
{
Response.Write{"colname:"+e.SortExpression);
//e.SortExpression will provide colomn name selected by user
SqlDataadaptor da=New SqlDataadapator("select*from Employee Orderby empname"+e.Sortexpression,con);

Dataset ds=New Dataset();

da.fill(ds,"Employee");

Gvemp.Datasource=ds.Table["Employee"];

Gvemp.DataBind();
}
Note:The similar code is required in page load and Grid view-sorting event Process .To avoid repetition using fallowing subprogram to fill grid view
void fillgrid(cname);

Title: How to highlight the Grid view row in asp.net
Here i will shown how to high lighting the name according to country.This requires Row data bound event of grid view control.Row data bound event will be executed towards each row construction with data from data source.This will provide access to row constructed
protected void Gridview-rowdataBound(..,..)
{
Response.Write(e.row.cells[4].Text+"");

if(e.Row.cells[4].Text=="Usa")

e.Row.Backcolor=system.drawing.color.Red;
}

Wednesday, November 30, 2011

Row edit,delete,update in grid view in asp.net using c#

Title: Edit,Delete,Update Data in Grid view in Asp.net using c#.net

Description:
As per previous articles we have seen how to export grid view data to excel in asp.net and how to bind data to drop down list in grid view.Now i would like to explain how to do edit,update in grid view using c#.Before going to start we have to set the grid view properties i:e(AutogenerateDeleteButton,AutogenerateEditButton,AutogenerateUpdateButton) to enable the auto generate Edit,Delete,Update buttons. The given example will show how to do the CRUD functionality on grid view data
Grid View properties:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="True">
</asp:GridView>

Bind the data to grid view:
//page load event
if(page.isPostback==false)
{
dataset ds=null;
ds=(dataset)session["ds1"];
//session will contain dataset ds1 with data selected by user
if(ds!=null)
{
gvemp.datasource=ds.Tables["employee"];
gvemp.DataBind();
}
}      
Row Editing:
When user clicks on edit button post backtakes place,row editing event of grid view will be executed.This event will provide row index
protected void gremp_rowediting(object sender,EventArgs e)
{
dataset ds=(dstaset)session["ds1"];
gvemp.editindex=e.new editindex;
//e.newedit index:- will be provide index of row for which edit button is selected
gvemp.Datasource=Ds.Table["employee"];
gvemp.Databind();
}
Row Updating:
This will perform post back,row-updating event procedure of grid view will be executed
protected void gvemp-rowupdating(Object sender,EvenArgs e)
{
Textbox txt=(Textbox)gvemp.Rows[e.RowIndex].cells[3].controls[0];
//here i will update the third cell data in grid view
int avg=int.parse(txt.Text);
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex]["Average"]=avg;
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
//it will overwrite the session of Dataset
//Rearrange Gridview
gvemp.editIndex=-1;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}
Row Deleting:
This will perform post back,row-deleting event procedure of grid view will be executed
protected void gvemp-rowdeleting(Object sender,EvenArgs e)
{
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex].Delete();
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}

Tuesday, November 29, 2011

Export data to excel in c#

Title:How to export grid view data to excel in asp.net using c#.net

Description:
Basically we can export the data to excel in two ways in asp.net with c#. One is using Download Format and Other one is using Microsoft.Office.Interop.Excel .In the Download format ,it  will render the grid view and export in XLST format.It is used when the data is export from grid view to excel.In Interop.Eexcel will create excel file dynamically and load the data into it.Exporting data to excel its pretty simple. Let's see how this can be done.For this i have taken data from database first then fill the existing data set.The following name space i have used for excel properties
Asp.Net Export to excel:
using Microsoft.Office.Interop.Excel;
Create Excel document:
Excel.Application App;
Excel.Workbook WorkBook;
Excel.Worksheet WorkSheet;
object misValue = System.Reflection.Missing.Value;
App = new Excel.Application();
WorkBook = App.Workbooks.Add(misValue);
WorkSheet = (Excel.Worksheet)WorkBook.Worksheets.get_Item(1);
Load the data into Excel file:
Here i will get the data into data set then it will load in to excel file using the following iteration.
for (int col = 0; col < dsreportdata.Tables[0].Columns.Count; col++)
{
for (int row = 0; row < dsreportdata.Tables[0].Rows.Count; row++)
{
WorkSheet.Cells[row + 12, col + 3] = dsreportdata.Tables[0].Rows[row].ItemArray[col].ToString();
}
}

Friday, November 25, 2011

XML data into Gridview in asp.net

Title:how to bind XML data in grid view in asp.net using C#.net

Description:
We have seen different examples on  how to bind data to Grid view in asp.net ,Import XML data to Grid View,bind data table to Grid view.Now i would like show how to bind the XML data to grid view.Before going to start  you may think we have to use XML classes to read the data,But we will not use any XML classes .In asp.net Data set has property to read the XML data which is Readxml().
XML Data:
<?xml version="1.0" encoding="utf-8" ?>
<Orders>
<Order>
<OrderId>1</OrderId>
<OrderName>Asp.net</OrderName>
<Phone>0000000000</Phone>
<Address>Hyd</Address>
<Amount>100</Amount>
</Order>
<Order>
<OrderId>2</OrderId>
<OrderName>Sharepoint</OrderName>
<Phone>1111111111</Phone>
<Address>USA</Address>
<Amount>200</Amount>
</Order>
<Order>
<OrderId>3</OrderId>
<OrderName>Jquery</OrderName>
<Phone>2222222222</Phone>
<Address>UK</Address>
<Amount>200</Amount>
</Order>
<Order>
<OrderId>4</OrderId>
<OrderName>Mvc</OrderName>
<Phone>4444444444</Phone>
<Address>AUS</Address>
<Amount>300</Amount>
</Order>
</Orders>

Aspx Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Bind XML data to Gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GVdynamicXML" runat="server" AutoGenerateColumns="False"
>
<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>
</form>
</body>
</html>

Code behind:
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 _XMLbindGridviewDefault3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet myDataSet = new DataSet();
myDataSet.ReadXml(Server.MapPath("~/XMLFile.xml"));
GVdynamicXML.DataSource = myDataSet;
GVdynamicXML.DataBind();
}
}
}
We should give a specific path of XML file to read the data using Readxml().Then bind the data  to grid view "gd_view"

Bel