Showing posts with label Gridview. Show all posts
Showing posts with label Gridview. Show all posts

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>

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

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

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"

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 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, May 7, 2012

How to manipulate the gridview cell

Here i will show how to manipulate the grid view cell styles in windows forms application.For this i will get all grid view rows and compare the grid view header cell value with drop down selected value. Then the related data cells back colour will be changed to Green.In foreach loop we have one more for loop to get the entire column cells of related header in grid view.

foreach(DataGridViewRow row in this.Gvorders.Rows)
{
if (row.HeaderCell.Value == txtorder.Text)
{
for (int i = 0; i < Gvorders.Columns.Count; i++)
{
this.Gvorders.CurrentCell = row.Cells[i];
row.Cells[i].Style.BackColor = Color.Green;
}
}
}
VB:
For Each row As DataGridViewRow In Me.Gvorders.Rows
 If row.HeaderCell.Value = txtorder.Text Then
  For i As Integer = 0 To Gvorders.Columns.Count - 1
   Me.Gvorders.CurrentCell = row.Cells(i)
   row.Cells(i).Style.BackColor = Color.Green
  Next
 End If
Next

Tuesday, March 27, 2012

Sharepoint List to gridview in sharepoint 2010

Here i will show how to access the the share point list data to Visual Web part in share point 2010 and the linq query is used to get the data from share point .Then Ive added the below code to web part user control.In can process the the list data to grid view
var Ldc = new SPLinqDataContext(SPContext.Current.Web.Url);
var Orderslist = Ldc.GetList("Orders");
var orederQueryResult = from order in orders where 
order.Dueate < DateTime.Now.AddMonths(6) select new { order.name, order.city, sname = order.name, DueDate =order.Date.Value.ToShortDateString() }; 
spGV.DataSource = orederQueryResult;
spGV.DataBind(); 
The above linq query gets order data based on orderdate
Using DataTable:
<asp:GridView ID="Gvdata" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" />
        <asp:BoundField DataField="Name" />
        <asp:BoundField DataField="DocumnetTYpe" />
        <asp:BoundField DataField="Role" />
        <asp:BoundField DataField="Key" />
    </Columns>
</asp:GridView>


using (SPSite s = new SPSite(url))
{
using (SPWeb sw = s.OpenWeb())
{
SPList sl = sw.Lists["Orders"];
DataTable ResTable = new DataTable();
ResTable.Columns.Add(new DataColumn("Id"));
ResTable.Columns.Add(new DataColumn("Name"));
ResTable.Columns.Add(new DataColumn("DocumentType"));
ResTable.Columns.Add(new DataColumn("Role"));
ResTable.Columns.Add(new DataColumn("Key"));
foreach (SPListItem item in sl.Items)
{
DataRow dr = ResTable.NewRow();
dr["Id"] = item.Id;
dr["Name"] = item.Name;
dr["DocumnetType"] = item.DocumnetType;
dr["Role"] = item.Role;
dr["Key"] = item.Key;
ResTable.Rows.Add(dr);
}
Gvdata.DataSource = ResTable;
Gvdata.DataBind();
}

Wednesday, March 14, 2012

Excel Data into grid view in asp.net

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

Description:
Reporting is the key features of any application.Because the end user wants the see the data what they want.
Some time we might need to import the data from files(Excel) ,then insert into data base.So i would like to explain one example for importing

Example:
The recent recent post have given the process of exporting.how to export grid view data to excel,Export Grid view Data to Word Document in asp.net,Export Grid view data to PDF document in asp.net,Import XML data to Grid View.Here i will show how to Import the Excel data to Grid view.For this i have used OLEDB connection to connect the excel database.Then get the data of sheet1 in to Data Adapter and fill the data set.Finally this data is bind to Grid view Excel to grid view in asp.net process:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvImpOrder"  AllowPaging="True" Runat="server" AutoGenerateColumns="False">
<asp:Button ID="btnImportOrders" runat="server" Text="Import excel Data" 
onclick="btnImportOrders_Click" /></div>
</form>
</body>
</html>

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

public partial class ImportExcelToGidview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnImportOrders_Click(object sender, EventArgs e)
{
String Con = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=D:\\ImportGidview\OrderReport.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection objCn = new OleDbConnection(con);
DataSet ds = new DataSet();
OleDbDataAdapter Oda = new OleDbDataAdapter("select * from[Sheet1$]", Con); 
Oda.Fill(ds);
GVImpOrder.DataSource = ds.Tables[0].DefaultView;
GVImpOrder.DataBind();
}
}

Wednesday, December 28, 2011

custom gridview in asp.net

Here i will show you how to create custom Data grid view and calculating total per entire column.For this i will go for create a data grid view control for accepting Products info and storing products write into Text file
code behind:
Imports System.IO
//form load event
DataGridView.RowCount=3
DataGridView.ColumnCount=3
DataGridView.Columns(0).HeaderText="desc"
DataGridView.Columns(1).HeaderText="Price"
DataGridView.Columns(2).HeaderText="Quantity"
DataGridView.Columns(3).HeaderText="Total"
End Sub
//calculating total Based on price,quantity
This requires "Cell Enter" event of DataGridView control,This event will provide current row index and column index
//This will executes when focus comes to cell
Private Sub dataGridView1_CellEnter(ByVal sender As Object, _
    ByVal e As DataGridViewCellEventArgs) _
    Handles dataGridView1.CellEnter

msgbox("row;"&e.RowIndex&&"col:"e.ColumnIndex)

if(e.ColumnIndex=3)Then
 With DataGridView1.Rows(e.RowIndex).cells(3).Value=Val(cells(2).Value)*val(cells(1).Value )
End With
total=quantity*price
with and end with will avoid repetition of DataGridiew.rows(e.RowIndex)

//logic for store into text file
private sub Button1_click(--)

Dim s As string
For i As Byte=0 to DataGridView1.Rows.Count-2
With DataGridView1.Rows(i)
s=s&DataGridView1.cells[0].Value&""&DataGridView1.cells[1].Value&""&DataGridView1.cells[2].Value&""&DataGridView1.cells[3].Value&
End With
Next

Dim sw As StreamWriter
sw=File.CreateText("Transinfo.txt)
sw.writeline("transeinfo "&vbCrLf&" "&"&vbCrLf&"&5
vbCrLf is visual basic carriage to return line feed[new line]
sw.Close()

End Sub

Change Grid view width Dynamically:
if (e.Row.RowType == DataControlRowType.Header) {
 for (i = 0; i <= e.Row.Cells.Count - 1; i++) {
  TableCell cell5 = e.Row.Cells(i);
  cell5.Width = new Unit("175px");
 }
}

Wednesday, December 21, 2011

Checkbox in grid view in asp.net||Check/Uncheck all check boxes in gridview

In previous articles i explained delete multiple rows in gridview using checkbox,Export Gridview Excel ,Export Gridview Data to PDF document,Export gridview to Word in asp.net.Grid view is providing different types of field for customization such as bound field,check box,image field,Hyperlink,Command,Template fields.Bound field is the default field for grid view.Here i will show how to use the check box inside grid view and add the value of selected row into Context.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<gridview autogeneratecolumns="False" id="gvOrdr" runat="server">
<columns>
<templatefield>
<itemtemplate>
<checkbox id="chkOrdr" runat="server"></checkbox>
</itemtemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkMainheadr"
OnCheckedChanged="chkMainheadr_OnCheckedChanged"
AutoPostBack="true" runat="server" />
</HeaderTemplate>

</templatefield>

<boundfield datafield="UserID" headertext="User ID">
<boundfield datafield="UserName" headertext="User Name">
<boundfield datafield="Role" headertext="Role">
</boundfield>

</columns>
</gridview></div></form>
</body>
</html>

Code behind:
In grid view Find Control method is provided which is access web server control with in the Template field.This return Obj type,it should be Type casted to Check Box type.So that property can be accessed.Here we will checked one check box then the value of particular row in to string using on OnCheckedChanged event
Note:We can add that string value to Text property controls like Text box,Label etc
Checked &unchecked All:
Here i have one check box in header template in aspx page.if check the header check box then all the check box should be checked .if unchecked the header check box then all the check box should be unchecked

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

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


protected void chkMainheadr_CheckedChanged(object sender, EventArgs e)
{
checkBox chkall =(CheckBox)Gvemp.HeaderRow.FindControl("chkMainheadr");
if (chkMainheadr.Checked == true)
{
foreach (GridViewRow gvOrdr in gvOrdr.Rows)
{
CheckBox chkIndividual =(CheckBox)gvOrdr.FindControl("chkOrdr");
chkIndividual.Checked = true;
}
}
else
{
foreach (GridViewRow gvOrdr in gvOrdr.Rows)
{
CheckBox chkIndividual = (CheckBox)gvOrdr.FindControl("chkOrdr");
chkIndividual.Checked = false;
}
}
}
}
Get the Selected CheckBox value in Gridview:
public void chk_OnCheckedChanged(object sender, EventArgs e)
  {
    string s;
    CheckBox chsubmit=(CheckBox)Gvemp.Rows[i].FindControl("chkOrdr");
    if(chsubmit.Checked)
    s=s+gvemp.Rows[i].cells[2].Text+;

  }
//place s variable in to context
  context.items.Add("sps",s);
 

Wednesday, December 14, 2011

link button in gridview in asp.net

Earlier  we learned how to export Gridview data to word document,gridview to excel,paging and sorting in Gridview.bind data to dropdownlist in gridview in asp.net.Here i will shown how to perform the data modifications(edit,delete) using link button in grid view in asp.net.Basically we have auto generated options to do edit and delete in grid view .But here i am using link button control with custom functionality in grid view .
Grid view having The Template field(asp:template field) which is used to add the any server controls and Bound field is used to bind the particulate field (cityid,city name) from data base to grid view columns from database .The bound fields has property to add the desirable column to it i.e Data Field
default.aspx:
<div>
<asp:panel cssclass="panel_set " id="Panel2" runat="server">
</asp:panel>

<br />
<table align="center" tablecen="" valign="center ><tbody>
<tr>  <td><br />
<asp:label id="lblcityid" runat="server" text="CityID:"></asp:label></td> <td><br />
<asp:textbox id="Txtcityid" readonly="True" runat="server"></asp:textbox></td>  </tr>
<tr> <td><br />
<asp:label id="lblcityname" runat="server" text="CityName:"></asp:label></td> <td><br />
<asp:textbox id="txtcityname" runat="server"></asp:textbox></td> </tr>
<tr> <td><br />
<asp:button id="btnsave" onclick="btnsave_Click" runat="server" text="Save">      <asp:button id="btnupdate" onclick="btnupdate_Click" runat="server" text="Update">  </asp:button></asp:button></td> </tr>
</tbody> </table>
<asp:panel cssclass="pnel_grv" id="panelgridviews" runat="server">
<asp:gridview autogeneratecolumns="False" cssclass="grid_scroll " datakeynames="cityid" emptydatatext="There is No Records To Display" id="grvcity" onrowdeleting="DeleteRecord" runat="server">
<columns>

<asp:boundfield datafield="cityid" headertext="cityid">
<itemstyle horizontalalign="Center" width="20px"></itemstyle>
</asp:boundfield>

<asp:boundfield datafield="cityname" headertext="cityname">
<itemstyle horizontalalign="Center" width="20px"></itemstyle>
</asp:boundfield>

<asp:templatefield>
<headertemplate> </headertemplate>
<itemtemplate>
<asp:linkbutton id="Linkedit" onclick="Linkedit_click" runat="server">Edit</asp:linkbutton>
</itemtemplate>
</asp:templatefield>
<asp:templatefield headertext="Delete?">
<itemtemplate>

<asp:linkbutton causesvalidation="false" commandname="Delete" id="lnBD" runat="server" text="Delete"></asp:linkbutton>

</itemtemplate>
</asp:templatefield>
</columns>
        
<footerstyle backcolor="#99CCCC" forecolor="#003399">
<pagerstyle backcolor="#99CCCC" forecolor="#003399" horizontalalign="Left">
<selectedrowstyle backcolor="#009999" font-bold="True" forecolor="#CCFF99">
<headerstyle backcolor="#003399" font-bold="True" forecolor="#CCCCFF">       
</headerstyle></selectedrowstyle></pagerstyle></footerstyle></asp:gridview>
</asp:panel>
</div>

Code behind:
Here one pop up is coming to confirmation to delete the record when we click on the delete link button in grid view.one more thing will have to observe here is how to delete record event is raised.The OnRowDeleting command which has given to grid view properties(can see in aspx page) is used to delete the record in grid view
//edit 
protected void Linkedit_click(object sender, EventArgs e)
  {
   LinkButton lnkButton = sender as LinkButton;
   GridViewRow row = (GridViewRow)lnkButton.NamingContainer;
   lblgdeptid.Text = row.Cells[0].Text;
   cmd = new SqlCommand("editcity", con);
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Add("cityid", SqlDbType.NVarChar).Value = lblgdeptid.Text;
   con.Open();
   SqlDataReader dr = cmd.ExecuteReader();
   if (dr.HasRows)
      {
       while (dr.Read())
             {
                Txtcityid.Text = dr["cityid"].ToString();
                txtcityname.Text = dr["cityname"].ToString();
              }
              dr.Close();
              con.Close();
        }
        else
        {
//give an pop with "there is no data"
        }
    }

//Delete

 protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    {
     int cityid = Int32.Parse(grvcity.DataKeys[e.RowIndex].Value.ToString());
     CityBAL3 pBAL = new CityBAL3();
     pBAL.City_Delete(cityid);
     grvcity.EditIndex = -1;
 
    }

Bel