Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Posts Tagged ‘Gridview’

Bind Silverlight Grid view with WCF Service

Posted by Viral Sarvaiya on September 17, 2010


Hello friends….

Here I demonstrate how to bind the grid view of the Silverlight with WCF Service.

You already know what is the Silverlight and WCF. My one post that demonstrate the use of the WCF Service with Silverlight, for more info about that check https://viralsarvaiya.wordpress.com/2010/08/26/use-of-wcf-service-in-silverlight/

Setp 1 : Create New Silverlight Project( here I give name of the project is “SilverlightGridTest”)

In the Visual Studio 2008 or 2010, file menu -> New -> project.

Select Silverlight application, give name as SilverlightGridTest and open the project.

Then check the checkbox true of the host the Silverlight application in web site.

Now you have 2 project in the solution.

Step 2: Database information

CREATE TABLE person (

Name VARCHAR(256),

Phone VARCHAR(50),

City VARCHAR(50)

)

make one procedure named “GetAllPersonInfo” and write the following Statement in the procedure

Select *from person order by name;

Step 3: Create WCF Service

Right click to SilverlightGridTest.web project, select add -> new item.

Choose Silverlight in left panel and choose Silverlight-enable WCF Service. Then give name “DataService.svc”

So Service has been added to project.

Here we have interface IDataService.cs and DataService will implements that so in our IDataService.cs code is as below.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SilverlightGridTest.Web

{

[ServiceContract]

public interface IDataService

{

[OperationContract]

PersonDetails GetPersonDetails();

}

[DataContract]

public class PersonDetails

{

List<Personinfo> _PersonList = new List<Personinfo>();

[DataMember]

public List<Personinfo> PersonIndex

{

get { return _PersonList; }

set { _PersonList = value; }

}

}

[DataContract]

public class Personinfo

{

[DataMember]

public string Name { get; set; }

[DataMember]

public string Phone { get; set; }

[DataMember]

public string City { get; set; }

}

}

In the “DataService.svc.cs” file write the following.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Data;

namespace SilverlightGridTest.Web

{

public class DataService : IDataService

{

public PersonDetails GetPersonDetails()

{

DatabaseHandler dbObj = new DatabaseHandler();

DataTable dataTablePersonInfo = dbObj.GetPersonInfo();

PersonDetails PersonDataMessage = new PersonDetails();

for (int iTagCounter = 0; iTagCounter < dataTablePersonInfo.Rows.Count; iTagCounter++)

{

Personinfo PersonInfo = new Personinfo();

PersonInfo.Name = dataTablePersonInfo.Rows[iTagCounter]["Name"].ToString();

PersonInfo.Phone = dataTablePersonInfo.Rows[iTagCounter]["Phone"].ToString();

PersonInfo.City = dataTablePersonInfo.Rows[iTagCounter]["City"].ToString();

PersonDataMessage.PersonIndex.Add(PersonInfo);

}

return PersonDataMessage;

}

}

}

Now add the new class name “DatabaseHandler.cs” for the operation on the database. Means this function will get the data from the database.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections.ObjectModel;

namespace SilverlightGridTest.Web

{

public class DatabaseHandler

{

private string _gConnectionString = ConfigurationManager.ConnectionStrings["Database"].ToString();

public DataTable GetPersonInfo()

{

SqlConnection sqlConnect = new SqlConnection(_gConnectionString);

sqlConnect.Open();

DataTable dbTbl = new DataTable();

//Get data

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "GetAllPersonInfo";

cmd.Connection = sqlConnect;

cmd.CommandType = CommandType.StoredProcedure;

SqlDataAdapter oAdapter = new SqlDataAdapter(cmd);

oAdapter.Fill(dbTbl);

sqlConnect.Close();

return dbTbl;

}

}

}

Step 4: Web.Config Settings

Database Connection string


<connectionStrings>

<add connectionString="packet size=4096;server=ServerName;persist security info=False;database=DatabaseName;uid=UserName;pwd=Password;" />

</connectionStrings>

Service Settings


<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior>

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="false" />

</behavior>

</serviceBehaviors>

</behaviors>

<bindings>

<customBinding>

<binding>

<binaryMessageEncoding />

<httpTransport />

</binding>

</customBinding>

</bindings>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

<services>

<service behaviorConfiguration="SilverlightGridTest.Web.TestServiceBehavior" name="SilverlightGridTest.Web.DataService">

<endpoint address="" binding="basicHttpBinding" contract="SilverlightGridTest.Web.IDataService" />

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

</service>

</services>

</system.serviceModel>

Step 5: Add clientaccesspolicy.xml and crossDomain.xml file.

This will complete the coding in the SilverlightGridTest.Web .

Build the application.

Now move to SilverlightGridTest.

Add the service reference and add the service which we develop above.

Step 6: Mainpage.xaml file.

Now in the Mainpage.xaml file put the grid control.


<UserControl x:Class="SilverlightGridTest.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">

<sdk:DataGrid x:Name="AllPerson" GridLinesVisibility="All" AutoGenerateColumns="False" >

<sdk:DataGrid.Columns>

<sdk:DataGridTextColumn Binding="{Binding Name}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" />

<sdk:DataGridTextColumn  Binding="{Binding Phone}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="Phone"/>

<sdk:DataGridTextColumn  Binding="{Binding City}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="City"/>

</sdk:DataGrid.Columns>

</sdk:DataGrid>

</Grid>

</UserControl>

Step 7 : Mainpage.xaml.cs file

Make the object of the service client, coding as follow.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using SilverlightGridTest.DataService;

namespace SilverlightGridTest

{

public partial class MainPage : UserControl

{

public DataServiceClient objDataService;

public MainPage()

{

InitializeComponent();

objDataService = new DataServiceClient();

objDataService.GetPersonDetailsCompleted += new EventHandler<GetPersonDetailsCompletedEventArgs>(objDataService_GetPersonDetailsCompleted);

objDataService.GetPersonDetailsAsync();

}

void objDataService_GetPersonDetailsCompleted(object sender, GetPersonDetailsCompletedEventArgs e)

{

AllPerson.ItemsSource = e.Result.PersonIndex;

}

}

}

Step 8: Run the application.

You will get the data will display in the grid as below

Enjoy coding…..

Posted in ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , , , , , , | 14 Comments »

ASP.NET Gridview: Merging Cells

Posted by Viral Sarvaiya on November 4, 2009


I had been searching for a way to merge cells in a GridView


If e.Row.DataItemIndex % 2 = 0 Then
e.Row.Cells(0).RowSpan = 2
e.Row.Cells(1).RowSpan = 2
End If
'Remove the extra cells created due to row span for odd rows
If e.Row.DataItemIndex % 2 = 1 Then
e.Row.Cells.RemoveAt(0)
e.Row.Cells.RemoveAt(0)
e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Center
End If

This code should take every cell in the first and second columns and merge it with the cell directly below it. Of course, this should be used very carefully, because you could screw up your data if each record does not have another corresponding record with it. However, this shouldn’t be too difficult to program around by adding data checks.

Posted in ASP.NET | Tagged: , , | Leave a Comment »

Export GridView Data into CSVFile In Asp.net

Posted by Viral Sarvaiya on October 30, 2009


Steps.

1) Create Simple Web Application.

2) put the below control in to the page (.aspx)

2.1) GridView (id= GridView1)

2.2) Button (id=button1 and Text =Create CSV File)

3) assign data source to GridView

4) on the button_click event put the following code.


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
'Create CSV file
Dim objSw As New StreamWriter(Server.MapPath("~/demo.csv"))
'get table from GridView1
Dim objDt As DataTable = DirectCast(GridView1.DataSource, DataSet).Tables(0)
'Get No Of Column in GridView
Dim NoOfColumn As Integer = objDt.Columns.Count
'Create Header
For i As Integer = 0 To NoOfColumn - 1
objSw.Write(objDt.Columns(i))
'check not last column
If i < NoOfColumn - 1 Then
objSw.Write(",")
End If
Next
objSw.Write(objSw.NewLine)
'Create Data
For Each dr As DataRow In objDt.Rows
For i As Integer = 0 To NoOfColumn - 1
objSw.Write(dr(i).ToString())

If i < NoOfColumn - 1 Then
objSw.Write(",")
End If
Next
objSw.Write(objSw.NewLine)
Next
objSw.Close()
Catch ex As Exception
Response.Write("Can Not Generate CSV File")
End Try
End Sub

Enjoy Coding….

Posted in ASP.NET | Tagged: , , , , , | 2 Comments »

custom paging of the datagrid or gridview

Posted by Viral Sarvaiya on August 20, 2009


hear i demonstrate the custom paging of the datagrid or gridview.

in the client side take the datagrid or grid view

here i take the datagrid,


<table>

<tr>
<td>

<asp:datagrid id="dgMake" runat="server" AutoGenerateColumns="False" Width="100%"
CellPadding="5" GridLines="None" AllowPaging="true">

<Columns>
<asp:TemplateColumn>
<HeaderStyle HorizontalAlign="Left" Width="100"></HeaderStyle>
<HeaderTemplate>Part</HeaderTemplate>
<ItemStyle HorizontalAlign="Left" Width="100"></ItemStyle>
<ItemTemplate><%#Container.DataItem("part")%></ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<HeaderTemplate>Description</HeaderTemplate>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
<ItemTemplate><%#Container.DataItem("description")%></ItemTemplate>
</asp:TemplateColumn>

</Columns>
<PagerStyle Visible="False"></PagerStyle>
</asp:datagrid>

</td>
</tr>

in the second raw, i add the link buttons as below,


<tr>
<td valign="top" align="right" bgcolor="#e1e4e6" style="padding:10px 10px 10px 60px;text-align:right;">
<asp:linkbutton id="FirstButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="0"> First Page</asp:linkbutton><asp:label id="lblFirstLine" runat="server">&nbsp;|&nbsp;</asp:label>
<asp:linkbutton id="PrevButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="prev">Prev</asp:linkbutton><asp:label id="lblLine" runat="server">&nbsp;|&nbsp;</asp:label>
<asp:linkbutton id="NextButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="next">Next</asp:linkbutton><asp:label id="lblLastLine" runat="server">&nbsp;|&nbsp;</asp:label>
<asp:linkbutton id="LastButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="last"> Last Page</asp:linkbutton>
</td>
</tr>

in the code-behind file, bind the datagrid as below,

define the page size of the datagrid in the page load


dgMake.PageSize = 50

then call this function in the postback false part of the page load.


sub bind_datagrid()

Dim ds As New DataSet

ds = classobject.fiunctionname()

If ds.Tables(0).Rows.Count > 0 Then

dgMake.DataSource = ds

dgMake.DataBind()

firstprev()

Else

dgMake.DataSource = ds
dgMake.DataBind()

FirstButton.Visible = False
PrevButton.Visible = False
NextButton.Visible = False
LastButton.Visible = False
lblFirstLine.Visible = False
lblLastLine.Visible = False
lblLine.Visible = False

End If
End Sub

Public Sub firstprev()
If dgMake.CurrentPageIndex <> 0 Then
Call Prev_Buttons()
FirstButton.Visible = True
PrevButton.Visible = True
lblFirstLine.Visible = True
Else
FirstButton.Visible = False
PrevButton.Visible = False
lblFirstLine.Visible = False
End If

'To Display Next/Last Page buttons

If dgMake.CurrentPageIndex <> (dgMake.PageCount - 1) Then
Call Next_Buttons()
NextButton.Visible = True
LastButton.Visible = True
lblLastLine.Visible = True
Else
NextButton.Visible = False
LastButton.Visible = False
lblLastLine.Visible = False
End If

If dgMake.CurrentPageIndex > 0 And dgMake.CurrentPageIndex < dgMake.PageCount - 1 Then
lblLine.Visible = True
Else
lblLine.Visible = False
End If

End Sub

Sub Prev_Buttons()
Dim PrevSet As String
If dgMake.CurrentPageIndex + 1 <> 1 Then
PrevSet = dgMake.PageSize
PrevButton.Text = ("Prev")
End If
End Sub

Sub Next_Buttons()
Dim NextSet As String
If dgMake.CurrentPageIndex + 1 < dgMake.PageCount Then
NextSet = dgMake.PageSize
NextButton.Text = ("Next")
End If
End Sub

Sub PagerButtonClick(ByVal sender As Object, ByVal e As EventArgs)
Dim arg As String = sender.CommandArgument
Select Case arg
Case "next"
'The next Button was Clicked
If (dgMake.CurrentPageIndex < (dgMake.PageCount - 1)) Then
dgMake.CurrentPageIndex += 1
End If

Case "prev"
'The prev button was clicked
If (dgMake.CurrentPageIndex > 0) Then
dgMake.CurrentPageIndex -= 1
End If

Case "last"
'The Last Page button was clicked
dgMake.CurrentPageIndex = (dgMake.PageCount - 1)

Case Else
'The First Page button was clicked
dgMake.CurrentPageIndex = Convert.ToInt32(arg)
End Select
'selpagecombo()
'Now, bind the data!
bind_datagrid()
End Sub

so the page will be bind to 50 records.

enjoy coding…..

Posted in ASP.NET | Tagged: , , | Leave a Comment »

Gridview – insert, update, delete

Posted by Viral Sarvaiya on July 27, 2009


Pre-requisites

Your project or website must be ASP.NET AJAX enabled website. Because we are going to add the GridView in an UpdatePanel. So your GridView control will be look smart without unnecessary postbacks. You need to create a Customer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type], with your desired data types. Then create a class file in your App_Code folder and create a Default.aspx along with code-behind file Default.aspx.cs.

Step 1. Create Class File ‘CustomersCls.cs’

We need to create a class file to do database manipulations such as select, insert, delete and update data in the Customer Table. So we add a class file as ‘CustomersCls.cs’ in App_Code section.

Let us write five methods in the class file as follows

public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
{
// Write your own Insert statement blocks
}
public DataTable Fetch()
{
// Write your own Fetch statement blocks, this method should return a DataTable
}
public DataTable FetchCustomerType()
{
// Write your own Fetch statement blocks to fetch Customer Type from its master table and this method

//should return a DataTable
}
public void Update(int CustomerCode, string CustomerName, string Gender, string City, string State,string CustomerType)
{
// Write your own Update statement blocks.
}
public void Delete(int CustomerCode)
{

// Write your own Delete statement blocks.
}

Step 2: Make Design File ‘Default.aspx’

In the Default.aspx page, add an UpdatePanel control. Inside the UpdatePanel, add a GridView, set AutoGenerateColumns as False. Change the ShowFooter Flag to True and set the DataKeyNames your column name for Customer Code and Customer Type, in our case it is Code and Type. Then click on the Smart Navigation Tag of the GridView control, choose Add New Column and add 5 BoundField columns with DataField values as Name, Gender, City, State and Type, plus 2 CommandField columns with one for Edit/Update and another for Delete functions. Now your GridView control is ready. But as first step, we need to add some new records into the database. For that we need to place the controls in the Footer row. So we have to convert all these BoundField columns as TemplateField columns. To do this again, click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open. Select column by column from Name to Customer Type, include also Edit column, and select ‘Convert this field into a TemplateField’. Now all the BoundField columns will be
converted to TemplateField columns except the Delete column.

Column[0] – Name

Right click on the GridView control, select Edit Template, choose column[0] – Name, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section. Add another Texbox in the FooterTemplate section and name it as txtNewName.

Column[1] – Gender

Now again select Edit Template, choose column[1] – Gender, replace the TextBox with a DropDownList,name it as cmbGender, add Male and Female as their ListItem values. On the Edit DataBindings of the cmbGender, add Eval(”Gender”) to its selectedvalue. Add another DropDownList in the FooterTemplate section and name it as cmbNewGender.

Column[2] –City & Column[3] – State

Add Texboxes in both column’s FooterTemplate section and name it as txtNewCity and txtNewState respectively.

Column[4] – Type

In this column’s EditItemTemplate section, replace the TextBox with a DropDownList, name it as cmbType. Also add another DropDownList in the FooterTemplate section and name it as cmbNewType. Both these DropDownList’s we are going to fill with dynamic data from database. So specify both DropDownList’s DataTextField and DataValueField as Type.

Column[5] – Edit

Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

For your persual, we have provided the complete source code of the GridView control below. The State column in our sample is read-only. So you cannot find TextBox for that column in the EditItemTemplate section.

Source Code of the GridView Control

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataKeyNames=”Code, Type”

OnRowCancelingEdit=”GridView1_RowCancelingEdit” OnRowDataBound=”GridView1_RowDataBound”

OnRowEditing=”GridView1_RowEditing” OnRowUpdating=”GridView1_RowUpdating”

OnRowCommand=”GridView1_RowCommand” ShowFooter=”True” OnRowDeleting=”GridView1_RowDeleting”>
<Columns>

<asp:TemplateField HeaderText=”Name” SortExpression=”Name”> <EditItemTemplate>
<asp:TextBox ID=”txtName” runat=”server” Text=’<%# Eval(”Name”) %>’></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtNewName” runat=”server”></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Bind(”Name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Gender”>
<EditItemTemplate>
<asp:DropDownList ID=”cmbGender” runat=”server” SelectedValue=’<%# Eval(”Gender”) %>’>
<asp:ListItem Value=”Male” Text=”Male”></asp:ListItem>
<asp:ListItem Value=”Female” Text=”Female”></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Eval(”Gender”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID=”cmbNewGender” runat=”server” >
<asp:ListItem Selected=”True” Text=”Male” Value=”Male”></asp:ListItem>
<asp:ListItem Text=”Female” Value=”Female”></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”City”>
<EditItemTemplate>
<asp:TextBox ID=”txtCity” runat=”server” Text=’<%# Bind(”City”) %>’></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtNewCity” runat=”server” ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID=”Label3″ runat=”server” Text=’<%# Bind(”City”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”State” SortExpression=”State”>
<EditItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Eval(”State”) %>’></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtNewState” runat=”server” ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID=”Label4″ runat=”server” Text=’<%# Bind(”State”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Type”>
<EditItemTemplate>
<asp:DropDownList ID=”cmbType” runat=”server” DataTextField=”Type” DataValueField=”Type”>

</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”Label5″ runat=”server” Text=’<%# Eval(”Type”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID=”cmbNewType” runat=”server” DataTextField=”Type” DataValueField=”Type”>

</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Edit” ShowHeader=”False”>
<EditItemTemplate>
<asp:LinkButton ID=”LinkButton1″ runat=”server” CausesValidation=”True” CommandName=”Update”

Text=”Update”></asp:LinkButton>
<asp:LinkButton ID=”LinkButton2″ runat=”server” CausesValidation=”False” CommandName=”Cancel”

Text=”Cancel”></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID=”LinkButton2″ runat=”server” CausesValidation=”False” CommandName=”AddNew”

Text=”Add New”></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID=”LinkButton1″ runat=”server” CausesValidation=”False” CommandName=”Edit”
Text=”Edit”></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText=”Delete” ShowDeleteButton=”True” ShowHeader=”True” />
</Columns>
</asp:GridView>

Step 3: Make Code-behind File ‘Default.aspx.cs’

Now we are going to do the code-behind part of this page. Les us explain you event by event coding on each methods. In the code-behind page, create an instance for the Customer class as follows

CustomersCls customer=new CustomersCls();

Then create a private method ‘FillCustomerInGrid’ to retrieve the existing customer list from the database and bind it to the GridView. The CustomersCls class’s Fetch() method is used and it returns the data to a DataTable. On first stage it will return empty rows. So you cannot see any header,data or even footer rows of the GridView control. You can only see an empty space or you see only the EmptyDataText. So you cannot add any new data from the footer row.

private void FillCustomerInGrid()
{
DataTable dtCustomer= customer.Fetch();

if (dtCustomer.Rows.Count>0)
{
GridView1.DataSource = dtCustomer;
GridView1.DataBind();
}
else
{
dtCustomer.Rows.Add(dtCustomer.NewRow());
GridView1.DataSource = dtCustomer;
GridView1.DataBind();</span>

int TotalColumns = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
GridView1.Rows[0].Cells[0].Text = “No Record Found”;
}
}

In this article, we have provided a workaround to fix this problem. Closely look at the method FillCustomerInGrid, there is a conditional statement to check the rows exists in DataTable or not.Now go to the else part of the if statement, see the block of code we provided there. Simply we have added an empty row to the DataTable. Then bind it to the GridView control. To give a professional look to the GridView control, we do little bit more by providing ColumnSpan and set a Text as “No Record Found”, this text will be displayed if the GridView is empty without any rows and you can see
both the Header and Footer of the GridView control.

Initialize GridView control

In the page load event, we have to call this FillCustomerInGrid method as follows,

protected void Page_Load(object sender, EventArgs e)
{
If (!IsPostBack)
{
FillCustomerInGrid();
}
}

Fill DropDownList in GridView with dynamic values

In column[4] – Type, there are two DropDownList controls, one in the EditItemTemplate section (cmbType) and another in FooterTemplate (cmbNewType). We have to fill both these DropDownList controls with some dynamic data. If you look at our CustomersCls class, we have a separate method called FetchCustomerType. In the RowDataBound event of the GridView control insert the following code.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbType = (DropDownList)e.Row.FindControl(”cmbType”);

if (cmbType != null)
{
cmbType.DataSource = customer.FetchCustomerType();
cmbType.DataBind();
cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}

if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList cmbNewType = (DropDownList)e.Row.FindControl(”cmbNewType”);
cmbNewType.DataSource = customer.FetchCustomerType();
cmbNewType.DataBind();
}
}

Previously in this article, we have set the DataKeyNames values as Code, Type. If you see in the above code, we use one of the DataKeyNames value as the SelectedValue for the cmbType control, this is to retain the value of the cmbType in EditMode. The index value of Code is 0 and Type is 1. So we use as follows

cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

So far we have initialized the GridView control with the datatable and also make some values to be filled in the Footer DropDownList cmbNewType. Run the application, you can see the GridView only with the Footer row and data in the cmbNewType control. Let us start to code for adding new records into the database when we click ‘Add New’ linkbutton.

Add New Records from GridView control

Create an event for the GridView’s RowCommand and add the following code in it.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals(”AddNew”))
{
TextBox txtNewName=(TextBox)GridView1.FooterRow.FindControl(”txtNewName”);
DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl(”cmbNewGender”);
TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl(”txtNewCity”);
TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl(”txtNewState”);
DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl(”cmbNewType”);

customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text,
cmbNewType.SelectedValue) ;
FillCustomerInGrid();
}
}

In the above code, we are declaring and finding the controls in the GridView’s footer section and use the CustomersCls class insert method to add the new data into the database. Then we are calling the FillCustomerInGrid method to fill the GridView control with the newly inserted values. Now save everything and run your application. Put some test data in the Textboxes and select some values in the DropDownLists and click on the Add New linkbutton. You can see data inserted into the database
and listed in the GridView control.

Edit and Update in GridView

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillCustomerInGrid();
}

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
FillCustomerInGrid();
}

You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl(”txtName”);
DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl(”cmbGender”);
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl(”txtCity”);
DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl(”cmbType”);

customer.Update(GridView1.DataKeys[e.RowIndex].Values[0].ToString(),txtName.Text,

cmbGender.SelectedValue,txtCity.Text,CustomerType.SelectedValue);
GridView1.EditIndex = -1;
FillCustomerInGrid();
}

The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the CustomersCls class Update method.

The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Code of the Customer. That is the unique code for each customer to perform update function.

Delete in GridView

To delete a row from the customer table, add the following lines of code in the GridView’s RowDeleting event. Here you have to pass the unique Code of customer which is in GridView1.DataKeys[e.RowIndex].Values[0].ToString() to the Delete method of the CustomersCls class.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
customer.Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
FillCustomerInGrid();
}

Posted in ASP.NET | Tagged: , , , , , | 2 Comments »

Print Data of GridView

Posted by Viral Sarvaiya on July 8, 2009


here is the steps:

1) create simple web application (here i used asp.net with C#).

2) put following control in to Page.

1) Gridview (id = GridView1)

2) html button (id =Button1)

<inputid=”Button1″type=”button”value=”Print”language=”javascript”onclick=”return Button1_onclick()” />
<asp:GridViewID=”GridView1″runat=”server”>
</asp:GridView>

3)  fill data into GridView

//here i used the list you  can bind with database also

System.Collections.Generic.List<string> obj = newSystem.Collections.Generic.List<string>();

for(inti = 0; i < 10; i++)
{
obj.Add(i.ToString());
}
GridView1.DataSource = obj;
GridView1.DataBind();

4) now write the print function. click on the Button1 or write Java Script.

<script language="javascript" type="text/javascript">
<!--
function Button1_onclick() {
//open new window set the height and width =0,set windows position at bottom
var a = window.open ('','','left =' + screen.width + ',top=' + screen.height + ',width=0,height=0,toolbar=0,scrollbars=0,status=0');
//write gridview data into newly open window
a.document.write(document.getElementById('<%= GridView1.ClientID %>').innerHTML);
a.document.close();
a.focus();
//call print
a.print();
a.close();
return false;
}
// -->
</script>

Posted in ASP.NET | Tagged: , | Leave a Comment »

 
%d bloggers like this: