The following code sample is for sorting a GridView formed With a DataSet.
Source: http://www.highoncoding.com/Articles/176_Sorting_GridView_Manually_.aspx
But it is not displaying any output.
There is no problem in sql connection.
I am unable to trace the error, please help me.
Thank You.
public partial class _Default : System.Web.UI.Page
{
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
private DataSet GetData()
{
SqlConnection cnn = new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", cnn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
aspx page
asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">
/asp:GridView>
Problem is with Page Load event when you fill the data you add it inside if(!IsPostBack) condition .
In this article, there is explained how to sort the GridView data in ASP.NET.
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well.
http://www.dotnetfunda.com/articles/article1598-how-to-sort-the-gridview-data-in-aspnet.aspx
//Code Behind
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvbind();
}
}
protected DataSet gvbind() // Binding the gridview using Dataset and I am using stored procedure "Proc_Displayinfo"
{
con.Open();
SqlCommand command = new SqlCommand("Proc_Displayinfo", con);
SqlDataAdapter adpt = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
return ds;
}
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void Gridview1_Sorting(object sender, GridViewSortEventArgs e)
{
gvbind();
DataTable dt = gvbind().Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
// Source Code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentId" onsorting="Gridview1_Sorting" AllowSorting="True">
<asp:TemplateField HeaderText="StudentID" SortExpression="StudentID">
<ItemTemplate>
<asp:Label ID="LBLStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TXTStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:TextBox>
</EditItemTemplate>
Related
How can I make a grid like in Excel in ASP.NET WebForms?
I would like rows and columns where user can enter data and after a click on a save button the data would be inserted into a database.
Hope this will help you out to full-fill your requirement.Here I am giving only aspx and c# coding. Create and modify your database and change the code accordingly.Here I am using direct insert statement you can use stored procedure.
Table in Database:-
page.aspx :-
<asp:GridView ID="excelgrd" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
<asp:BoundField DataField="Slno" HeaderText="SL No" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txnm" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txdesc" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="svbtn" runat="server" Text="Save" OnClick="svbtn_Click" />`
code behind of your page :-
`
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
bindgrd();//bind your grid
}
}
private void bindgrd()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Slno", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Desc", typeof(string)));
dr = dt.NewRow();
dr["Slno"] = 1;
dr["Name"] = string.Empty;
dr["Desc"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
excelgrd.DataSource = dt;
excelgrd.DataBind();
}
protected void addnewrow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["Slno"] = i + 1;
dtCurrentTable.Rows[i - 1]["Name"] = tx1.Text;
dtCurrentTable.Rows[i - 1]["Desc"] = tx2.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
excelgrd.DataSource = dtCurrentTable;
excelgrd.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");
tx1.Text = dt.Rows[i]["Name"].ToString();
tx2.Text = dt.Rows[i]["Desc"].ToString();
rowIndex++;
}
}
}
}
protected void svbtn_Click(object sender, EventArgs e)
{
foreach(GridViewRow r in excelgrd.Rows)
{
string des =(r.FindControl("txdesc") as TextBox).Text;
string nm = (r.FindControl("txnm") as TextBox).Text;
try
{
con.Open();
SqlCommand sql = new SqlCommand("insert into test (name,name_desc) values('"+nm+"','"+des+"')", con);
sql.ExecuteNonQuery();
sql.Dispose();
}
catch (Exception e1)
{
string error = e1.ToString();
}
finally
{
con.Close();
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
addnewrow();
}`
I have a DropDownList which has a list of tables. Under it there is GridView. Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically.
Following is my bind method. I have two problems:
I couldn’t wrap the binding part in if (!IsPostBack) since the GridView is populated based on the selection of the DropDownList, so everytime I change the selection, the columns will be duplicated.
And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?
My bind method
private void BindGridView()
{
DataSet ds = new DataSet();
try
{
ds = …
if (ds.Tables.Count > 0)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
TemplateField tField = new TemplateField();
tField.HeaderText = dc.ColumnName;
GridView2.Columns.Add(tField);
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
else
{
…
}
}
catch (Exception ex)
{
…
}
}
There are various steps that should be taken care of:
STEP I::
Create a class inheriting the ITemplate interface. Override the method InstantiateIn() of the ITemplate interface.
STEP II:
Define a constructor for your class that takes a ListItemType object as its parameter.
STEP III::
If the Control being added to the container's ControlCollection has to be bound to some DataSource Column, then register the
handler for the OnDataBinding event. When the event occurs, retrieve the text from the data source and assign it to your control. For Example, hyprLnk_DataBinding event is defined for Binding Data to your controls created inside ItemTemplate.
public class TemplateGenerator : ITemplate // Class inheriting ITemplate
{
ListItemType type;
string columnName;
public TemplateGenerator(ListItemType t, string cN)
{
type = t;
columnName= cN;
}
// Override InstantiateIn() method
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (type)
{
case ListItemType.Item:
HyperLink hyprLnk = new HyperLink();
hyprLnk.Target = "_blank"; //Optional.
hyprLnk.DataBinding+=new EventHandler(hyprLnk_DataBinding);
container.Controls.Add(hyprLnk);
break;
}
}
// The DataBinding event of your controls
void hyprLnk_DataBinding(object sender, EventArgs e)
{
HyperLink hyprlnk = (HyperLink)sender;
GridViewRow container = (GridViewRow)hyprlnk.NamingContainer;
object bindValue = DataBinder.Eval(container.DataItem,columnName);
// Adding check in case Column allows null values
if (bindValue != DBNull.Value)
{
hyprlnk.Text = bindValue.ToString();
hyprlnk.NavigateUrl = "http://www.google.com";
}
}
}
That's all. Above was just a sample to create ItemTemplate dynamically for GridView and add controls to the Item Template.
Now, Below is the function that will actually carry out the calls to create Template Columns dynamically. You can call this function when required for e.g. from your DropDownList event Handler.
protected void GenerateGridViewColumnsDynamically()
{
// Create the TemplateField
TemplateField firstName = new TemplateField();
firstName.HeaderText = "First_Name";
firstName.ItemTemplate = new TemplateGenerator(ListItemType.Item, "FirstName");
// Showing boundField example just for more context
BoundField lastName = new BoundField();
lastName.DataField = "LastName";
lastName.HeaderText = "Last_Name";
// Add the Columns now
MyGridView.Columns.Add(firstName);
MyGridView.Columns.Add(lastName);
}
NOTE:: FirstName and LastName are the Columns whose Names are passed to the constructor of your custom class: TemplateGenerator.
I have done the same functionality as below with custom paging(using storedProc) for 100+ million records in many tables, update, delete and insert also:
CREATE PROCEDURE [dbo].[sp_Mk]
#PageIndex INT,
#PageSize INT,
#tableName nvarchar(255),
#totalRow INT Output
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
Declare #anotherSql NVARCHAR(1000)
DECLARE #ParamDefinition NVARCHAR(500)
--DECLARE #totalRow INT
Set #sql = 'WITH TempResult AS( SELECT * FROM '+#tableName+'), TempCount AS ( SELECT COUNT(*) AS MaxRows FROM TempResult )
SELECT * FROM TempResult, TempCount ORDER BY (Select Null)
OFFSET '+CONVERT(VARCHAR(20),(#PageIndex-1)*#PageSize) +' ROWS FETCH NEXT '+CONVERT(VARCHAR(20),#PageSize)+' ROWS ONLY'
PRINT #SQL
EXECUTE sp_executesql #SQL
Set #anotherSql=N'SELECT COUNT(*) as totalRow FROM '+#tableName
SET #ParamDefinition = N'#totalRowOutPut INT OUTPUT'
--PRINT #anotherSql
Execute sp_executesql #anotherSql,
#ParamDefinition,
--#tableNameInput=#tableName,
#totalRowOutPut=#totalRow OUTPUT
End
<asp:GridView CssClass="table-striped header-fixed" ID="grdDynamic" runat="server" AutoGenerateColumns="True" ShowHeaderWhenEmpty="true" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
OnRowEditing="OnRowEditing_grdDynamic" OnRowUpdating="OnRowUpdating_grdDynamic" OnRowCancelingEdit="OnRowCancelingEdit_grdDynamic" OnRowDeleting="OnRowDeleting_grdDynamic" OnRowDataBound="OnRowDataBound_grdDynamic">
</asp:GridView><br/>
<asp:linkbutton id="AddButton" runat="server" commandname="Add" text="Insert: " OnClick="AddNewButton_Click" /><br/>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" CssClass="pagination-ys" runat="server" Text = '<%#Eval("Text") %>' CommandArgument = '<%# Eval("Value") %>' Enabled = '<%# Eval("Enabled") %>' OnClick = "Page_Changed"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater><asp:HiddenField runat="server" id="hdnPageIndex" Value="1"></asp:HiddenField>
SqlConnectionStringBuilder builder;
int pageSize = 100;
protected void Page_Load(object sender, EventArgs e)
{
builder = new SqlConnectionStringBuilder(connectionString);
if (!IsPostBack)
{
using (SqlConnection connObj = new SqlConnection(connectionString))
{
connObj.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='" + builder.InitialCatalog + "' AND TABLE_NAME Not In('AspNetUsers') Order By TABLE_NAME", connObj))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
ddlTableNames.DataSource = ds;
ddlTableNames.DataBind();
ddlTableNames.Items.Insert(0, new ListItem("Select Table", String.Empty));
}
}
}
//}
//else if(ddlTableNames.Visible) ddlTableNames.Visible = false;
}
protected void ddlTableNames_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlTableNames.SelectedValue != "")
{
grdDynamic.Visible = true;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
else if (grdDynamic.Visible == true) grdDynamic.Visible = false;
}
private void BindGrid(string selectedTable, int pageIndex, bool addNewRow=false)
{
using (SqlConnection connObj = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_Mk", connObj))
{
int recordCount=0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", pageSize);
cmd.Parameters.AddWithValue("#tableName", ddlTableNames.SelectedValue);
SqlParameter totalRow = new SqlParameter("#totalRow", SqlDbType.Int, 4);
totalRow.Direction = ParameterDirection.Output;
cmd.Parameters.Add(totalRow);
connObj.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
grdDynamic.DataSource = ds.Tables[0];
if (addNewRow) ds.Tables[0].Rows.Add();
recordCount = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);
grdDynamic.DataBind();
connObj.Close();
if (totalRow.Value != DBNull.Value)
{
}
this.PopulatePager(recordCount, pageIndex);
}
}
}
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / pageSize);
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
pages.Add(new ListItem("First", "1", currentPage > 1));
for (int i = 1; i <= pageCount; i++)
{
ListItem item=new ListItem(i.ToString(), i.ToString(), i != currentPage);
if (i == currentPage) item.Attributes.Add("style", "color:red;");
pages.Add(item);
}
pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
hdnPageIndex.Value = pageIndex.ToString();
this.BindGrid(ddlTableNames.SelectedValue, pageIndex);
}
protected void OnRowEditing_grdDynamic(object sender, GridViewEditEventArgs e)
{
grdDynamic.EditIndex = e.NewEditIndex;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowUpdating_grdDynamic(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = grdDynamic.Rows[e.RowIndex];
string updateStatement = string.Empty;
for (int x = 0; x < row.Cells.Count; x++) updateStatement = updateStatement + grdDynamic.DataKeys[e.RowIndex].Values[x] + " = " + grdDynamic.DataKeys[e.RowIndex].Values[x] + ", ";
//int recordId = Convert.ToInt32(grdDynamic.DataKeys[e.RowIndex].Values[0]);
using (SqlConnection con = new SqlConnection(connectionString))
{
//using (SqlCommand cmd = new SqlCommand("UPDATE "+selectedTable"+ SET Name = #Name, Country = #Country WHERE CustomerId = #CustomerId"))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
grdDynamic.EditIndex = -1;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowCancelingEdit_grdDynamic(object sender, EventArgs e)
{
grdDynamic.EditIndex = -1;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowDeleting_grdDynamic(object sender, GridViewDeleteEventArgs e)
{
int recordId = Convert.ToInt32(grdDynamic.DataKeys[e.RowIndex].Values[0]);
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM " + ddlTableNames.SelectedValue + " WHERE RecordId = #recordId"))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void btnGo_Click(object sender, EventArgs e)
{ int myInt;
if(txtPageSize.Text!=null && txtPageSize.Text !=string.Empty)
if(int.TryParse(txtPageSize.Text, out myInt)) pageSize = myInt;
hdnPageIndex.Value = "1";
this.BindGrid(ddlTableNames.SelectedValue, 1);
}
protected void AddNewButton_Click(object sender, EventArgs e)
{
hdnPageIndex.Value="1";
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value), true);
}
protected void OnRowDataBound_grdDynamic(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != grdDynamic.EditIndex)
{
(e.Row.Cells[0].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
Hope it helps:
the problem is if iam sorting with employee field assending or desending it is sorting perfectly if iam pressing next or previous button it is sorting assending order and displaying only in assending order can any body help tp how to bind gridview data at GridView1_PageIndexChanging() event to work perfectly
this is my default3.aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
AutoGenerateColumns="False" onsorting="GridView1_Sorting"
CurrentSortField="employeeid" CurrentSortDirection="ASC"
onrowcreated="GridView1_RowCreated" AllowPaging="true"
CaptionAlign="Bottom" onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender"
PageSize="2">
<Columns>
<asp:BoundField DataField="EmployeeId" HeaderText="Last Name"
ItemStyle-Width="15%" SortExpression="EmployeeId" >
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="First Name" ItemStyle-Width="15%"
SortExpression="Name" >
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="gender" HeaderText="Email" ItemStyle-Width="15%" >
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Change Password" ItemStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="imgbtn1" runat="server">change password</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="15%"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="city" HeaderText="Date created" ItemStyle-Width="15%">
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
</Columns>
<PagerSettings Mode="NextPreviousFirstLast" />
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/images/up_arrow.png" Width="10px" />
</form>
</body>
</html>
this is my default.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string gender { get; set; }
public string city { get; set; }
}
public static DataSet getallemployees()
{
String cs = "Data Source=.;database=users;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from tblEmployees", con);
SqlDataAdapter da = new SqlDataAdapter("select * from tblEmployees", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public static List<Employee> GetAllEmployees1(string sortColumn)
{
List<Employee> listEmployees = new List<Employee>();
String cs = "Data Source=.;database=users;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery = "select * from tblEmployees";
if (!string.IsNullOrEmpty(sortColumn))
{
sqlQuery += " order by " + sortColumn;
}
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.EmployeeId = Convert.ToInt32(rdr["Employeeid"]);
employee.Name = rdr["name"].ToString();
employee.Name = rdr["gender"].ToString();
employee.Name = rdr["city"].ToString();
listEmployees.Add(employee);
}
rdr.Close();
}
return listEmployees;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource= GetAllEmployees1("employeeid");
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SortDirection sortDirection = SortDirection.Ascending;
string sortField = string.Empty;
SortGridview(GridView1, e, out sortDirection, out sortField);
string strsortDirection = sortDirection == SortDirection.Ascending ? "ASC" : "DESC";
GridView1.DataSource = GetAllEmployees1(e.SortExpression + " " + strsortDirection);
GridView1.DataBind();
}
private void SortGridview(GridView gridview, GridViewSortEventArgs e, out SortDirection sortDirection, out string sortField)
{
sortField = e.SortExpression;
sortDirection = e.SortDirection;
if (gridview.Attributes["CurrentSortField"] != null && gridview.Attributes["CurrentSortDirection"] != null)
{
if (sortField == gridview.Attributes["CurrentSortField"])
{
if (gridview.Attributes["CurrentSortDirection"] == "ASC")
{
sortDirection = SortDirection.Descending;
}
else
{
sortDirection = SortDirection.Ascending;
}
}
gridview.Attributes["CurrentSortField"] = sortField;
gridview.Attributes["CurrentSortDirection"] = (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (GridView1.Attributes["CurrentSortField"] != null && GridView1.Attributes["CurrentSortDirection"] != null)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell tableCell in e.Row.Cells)
{
if (tableCell.HasControls())
{
LinkButton sortLinkButton = null;
if (tableCell.Controls[0] is LinkButton)
{
sortLinkButton = (LinkButton)tableCell.Controls[0];
}
if (sortLinkButton != null && GridView1.Attributes["CurrentSortField"] == sortLinkButton.CommandArgument)
{
Image image = new Image();
if (GridView1.Attributes["CurrentSortDirection"] == "ASC")
{
image.ImageUrl = "~/images/down_arrow.png";
image.Width = 10;
image.Height = 10;
}
else
{
image.ImageUrl = "~/images/~/images/up_arrow.png";
image.Width = 10;
image.Height = 10;
}
tableCell.Controls.Add(new LiteralControl(" "));
tableCell.Controls.Add(image);
}
}
}
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
Label1.Text = "Displaying Page " + (GridView1.PageIndex + 1).ToString() + " of " + GridView1.PageCount.ToString();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = getallemployees();
GridView1.DataBind();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class viewstate_dataset : System.Web.UI.Page
{
public DataSet getallemployees
{
get{
if (ViewState["Empdetails"] == null)
{
String cs = "Data Source=.;database=users;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from tblEmployees", con);
SqlDataAdapter da = new SqlDataAdapter("select EmployeeId,Name,gender+','+Name as gender,city from tblEmployees", con);
DataSet ds = new DataSet();
da.Fill(ds);
ViewState["Empdetails"] = ds;
}
} return (DataSet)ViewState["Empdetails"];
}
set
{
ViewState["Empdetails"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = getallemployees;
GridView1.DataBind();
Session["sortDirection"] = SortDirection.Descending;
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortexp=e.SortExpression;
Session["sortexp"] = sortexp;
if (Session["sortDirection"] != null && Session["sortDirection"].ToString() == SortDirection.Descending.ToString())
{
Session["sortDirection"] = SortDirection.Ascending;
sort (sortexp, "ASC");
}
else
{
Session["sortDirection"] = SortDirection.Descending;
sort(sortexp, "DESC");
}
}
private void sort(string soreExpression, string p)
{
DataView dv = null;
dv = new DataView(getallemployees.Tables[0]);
dv.Sort = soreExpression + " " + p;
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string sortExp = string.Empty;
string NewSortDirection = string.Empty;
GridView1.PageIndex = e.NewPageIndex;
if (Session["sortexp"] != null)
{
sortExp = (string)Session["sortexp"];
if (Session["sortDirection"] != null && Session["sortDirection"].ToString() == SortDirection.Ascending.ToString())
{
NewSortDirection = "ASC";
}
else
{
NewSortDirection = "DESC";
}
sort(sortExp, NewSortDirection);
}
else
{
GridView1.DataSource = getallemployees;
GridView1.DataBind();
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (GridView1.Attributes["sortexp"] != null && Session["sortDirection"] != null)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell tableCell in e.Row.Cells)
{
if (tableCell.HasControls())
{
LinkButton sortLinkButton = null;
if (tableCell.Controls[0] is LinkButton)
{
sortLinkButton = (LinkButton)tableCell.Controls[0];
}
if (sortLinkButton != null && Session["sortexp"].ToString() == sortLinkButton.CommandArgument)
{
Image image = new Image();
if (Session["sortDirection"].ToString() == "ASC")
{
image.ImageUrl = "~/images/down_arrow.png";
image.Width = 10;
image.Height = 10;
}
else
{
image.ImageUrl = "~/images/up_arrow.png";
image.Width = 10;
image.Height = 10;
}
tableCell.Controls.Add(new LiteralControl(" "));
tableCell.Controls.Add(image);
}
}
}
}
}
}
}
but while sort data uparrow and down arrow is not coming on the header columns pls any body help me
The problem is you are calling getallemployees() on GridView1_PageIndexChanging function which ofcourse is returning unsorted data for next page.
In order to resolve this issue, you need to use ViewState for your data to be persistant.
Following solution will greatly help you out in sorting your grid using ViewState
http://www.stackoverflow.com/questions/702600/sorting-and-paging-with-gridview-asp-net?rq=1
I got the below code from internet. It is working properly. I have added paging also. When I'm just sorting, it is working properly. When I am changing the page index, the sorting is lost.
Here is the client side code that set a gridview with 20 items per page, using the sort linked to the "GridView1_Sorting" method in the server side code.
Client side
<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False" PageSize="20" AllowPaging="True" AllowSorting="True" OnSorting="GridView1_Sorting" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="Employee no" SortExpression="eno">
<ItemTemplate>
<%#Eval("eno")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp name" SortExpression="empname">
<ItemTemplate>
<%#Eval("empname")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<ItemTemplate>
<%#Eval("sal")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now the server side code:
Server side
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string GetSortDirection()
{
switch (GVSortDirection)
{
case "ASC":
GVSortDirection = "DESC";
break;
//assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
string sortDirection = GetSortDirection();
dataView.Sort = e.SortExpression + " " + sortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridData();
}
}
When you page, the PageIndexChanging event is called. This in turn runs the GridData() procedure, which sets the data source for the gridview to be a data table containing records from the emp table, with no particular sort order.
What you should do is to take the code that you've written in your GridView1_Sorting event-handler, and include this within the GridData routine, so that whenever the grid is populated with data - whether when the page first loads, when the page index is changed or when the gridview is sorted - the gridview is based on a sorted dataview, rather than an unsorted data table.
The way you are maintaining SortDirection using GetSortDirection, in same fashion maintain SortExpression.
Happy coding!!!
Have a look to this article, may you will get what you want
I'm trying to get a gridview to sort and page manually with no success.
The problem is that when a user clicks the column they want to sort, it sorts that page, but doesn't sort the datasource (dataview) behind the gridview. So when they progress to a different page, their sort is lost. Pretty much I'm looking for a sort that will actually sort the datasource behind the gridview. Here is what I have so far:
protected void GridView_OnSort(object sender, GridViewSortEventArgs e)
{
String sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
DataView myDataView = new DataView(mybll.GetItemsOrdered());
myDataView.Sort = sortExpression + " DESC";
GridView.DataSource = myDataView;
GridView.DataBind();
}
else
{
DataView myDataView = new DataView(mybll.GetItemsOrdered());
myDataView.Sort = sortExpression + " ASC";
GridView.DataSource = myDataView;
GridView.DataBind();
}
}
Any help would be appreciated. Thanks.
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
http://www.netomatix.com/development/GridViewSorting.aspx
<asp:GridView
ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true">
<Columns>
<asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid" />
<asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
<asp:BoundField DataField="writer" HeaderText="WRITER" />
<asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook" />
<asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
if (DT != null) {
DataView dataView = new DataView(DT);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string GridViewSortDirection {
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string ConvertSortDirectionToSql(SortDirection sortDirection) {
switch (GridViewSortDirection) {
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
}
Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.
The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.
There are other methods, too, such as persisting user profiles.
I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx
To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
I found a much easier way, which allows you to still use the built in sorting/paging of the standard gridview...
create 2 labels. set them to be visible = false. I called mine lblSort1 and lblSortDirection1
then code 2 simple events... the page sorting, which writes to the text of the invisible labels, and the page index changing, which uses them...
Private Sub gridview_Sorting(sender As Object, e As GridViewSortEventArgs) Handles gridview.Sorting
lblSort1.Text = e.SortExpression
lblSortDirection1.Text = e.SortDirection
End Sub
Private Sub gridview_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gridview.PageIndexChanging
gridview.Sort(lblSort1.Text, CInt(lblSortDirection1.Text))
End Sub
this is a little sloppier than using global variables, but I've found with asp especially that global vars are, well, unreliable...
More simple way...:
Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
Dim dv As New DataView(dt)
If GridView1.Attributes("dir") = SortDirection.Ascending Then
dv.Sort = e.SortExpression & " DESC"
GridView1.Attributes("dir") = SortDirection.Descending
Else
GridView1.Attributes("dir") = SortDirection.Ascending
dv.Sort = e.SortExpression & " ASC"
End If
GridView1.DataSource = dv
GridView1.DataBind()