Cast DataRowView as a typed row? - asp.net

-update start
Unable to cast object of type 'namespace.Student' to type 'System.Data.DataRowView'
<%# FixNull(((System.Data.DataRowView)Container.DataItem).Row, "Name")%>
protected string FixNull(DataRow dr, string fieldName)
{
if (dr != null)
{
if (!dr.IsNull(fieldName))
return (dr[fieldName]).ToString(); }
return " ";
}
-update end
in the below method expecting an object, so how would i cast it to that type? i always get null no matter what column.
calling from .aspx:
<%# FixNull((mynamespace.Student)(Container.DataItem), "CreatedBy")%>
.CS
protected string FixNull(object dataItem, string fieldName)
{
if (dataItem != null)
{
DataRowView drv = (DataRowView)dataItem;
if (drv != null) //always getting null
{
if (!drv.Row.IsNull(fieldName))
return (drv[fieldName]).ToString();
}
}
return " ";
}

here is how should be done:
<%# Eval("Name") == null ? " " : Eval("Name")%>

Get the help from this article:
http://www.codeproject.com/Articles/38669/Using-Formatting-Functions-with-GridView-Template-.aspx
Updated...
Try the given code:
ASPX:
<asp:GridView ID="gvSample" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="ID" HeaderStyle-Width="100px">
<ItemTemplate>
<%# FixNull(Container.DataItem ,"ID") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Code" HeaderStyle-Width="100px">
<ItemTemplate>
<%# FixNull(((System.Data.DataRowView)Container.DataItem).Row, "Code") %> <!--updated here-->
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
gvSample.DataSource = GetData();
gvSample.DataBind();
}
private DataTable GetData()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("Code", typeof(string)));
DataRow dr;
dr = dt.NewRow();
dr["ID"] = 1;
dr["Code"] = null;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["Code"] = "Karan";
dt.Rows.Add(dr);
return dt;
}
protected string FixNull(object dataItem,string fieldname)
{
if (dataItem != null)
{
//updated here
//DataRowView drv = (DataRowView)dataItem;
//if (drv != null)
//{
// if (!drv.Row.IsNull(fieldname))
// return (drv[fieldname]).ToString();
//}
DataRowView drv;
DataRow dr;
if (dataItem is DataRowView)
{
drv = (DataRowView)dataItem;
if (drv != null)
{
if (!drv.Row.IsNull(fieldname))
return (drv[fieldname]).ToString();
}
}
if (dataItem is DataRow)
{
dr = (DataRow)dataItem;
if (dr != null)
{
if (!dr.IsNull(fieldname))
return dr[fieldname].ToString();
}
}
}
return " ";
}

Related

Loosing Attributes in DropDownList asp.net

I set attributes into a dropdownlist
the problem is that when I try to read them in a button click I get null !!
I am not sure of this is something to do with the postback or not but you will see my code below
Why is that and how to fix it?
This is my Code
protected void ddlReps_DataBound(object sender, EventArgs e)
{
foreach (System.Data.DataRow row in dt.Rows)
{
ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportPath", row["ReportPath"].ToString());
ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportServer", row["ReportServer"].ToString());
}
string AttribValue1 = ddlReps.SelectedItem.Attributes["ReportPath"];
//When I check here I can see the valu
}
protected void btnViewReport_Click(object sender, EventArgs e)
{
string AttribValue2 = ddlReps.SelectedItem.Attributes["ReportPath"];
//Here is null :(
}
ALso here is the page load code
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated) // if the user is already logged in
{
Response.Redirect("~/AccessDenied.aspx");
}
if (!Page.IsPostBack)
{
if (Session["USERNAME"] != null)
{
lblWelcome.Text = "Welcome back " + Session["USERNAME"].ToString();
}
string connStr = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("mySP", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//Populate your DropDownList
ddlReps.DataSource = dt;
ddlReps.DataTextField = "ReportName";
ddlReps.DataValueField = "ReportID";
ddlReps.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
and here is the markeup for the ddl
the asp:ScriptManager is used because i am using ReportViewer
<div>
<form id="form2" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="report-module">
<h2>Choose your report</h2>
<asp:DropDownList ID="ddlReps" runat="server" OnDataBound="ddlReps_DataBound" CssClass="ddl" ViewStateMode="Enabled"></asp:DropDownList>
</div>
<rsweb:ReportViewer ID="reportViewer" runat="server" Width="100%" ProcessingMode="Remote" Font-Names="sans-serif" Font-Size="8pt" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Height="457px" BackColor="White" Visible="False" SplitterBackColor="51, 181, 229">
</rsweb:ReportViewer>
</form>
</div>

How can I make Excel like grid in asp.net C# Webform

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

asp.net gridview sorting and paging

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

How to make asp:GridView sortable?

i have an asp:GridView control, which i've set the AllowSorting="True" property on:
<asp:GridView ID="gridUsers" runat="server" PageSize="100" ShowHeaderWhenEmpty="True"
Width="100%" AllowSorting="True" onrowcreated="gridUsers_RowCreated"
onsorting="gridUsers_Sorting">
</asp:GridView>
At design time the grid looks sortable:
But at runtime only the middle column is sortable:
How do i make an asp:GridView sortable in ASP.NET?
Note: The asp:GridView with AllowSorting requires a Sorting event handler to be present:
protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
//asp:GridView will throw an exception if a Sorting event handler isn't present
}
Update: i realized what's special about the Description column. It's the only column whose display name is correct from the database as-is. The remaining columns i have to fix the display name to be presentable:
protected void gridUsers_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; //UserGUID
e.Row.Cells[1].Text = "User name";
e.Row.Cells[2].Text = "Full name";
//3=Description
e.Row.Cells[4].Text = "E-mail";
e.Row.Cells[5].Text = "Active";
e.Row.Cells[5].Visible = false;
e.Row.Cells[6].Text = "Account type";
}
Now i just have to figure out the tricky part; and make columns sortable.
this code will definitely help you:
In the GridView, Make the Property AllowSorting = "True" and in the GridView Columns give like this
<asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />
and also use the below coding:
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
string sortExpression = e.SortExpression;
ViewState["z_sortexpresion"] = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC");
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
private void SortGridView(string sortExpression, string direction)
{
DTSorting = new DataView(DTSorting, "", sortExpression + " " + direction, DataViewRowState.CurrentRows).ToTable();
gv.DataSource = DTSorting;
gv.DataBind();
}
public DataTable DTSorting
{
get
{
if (ViewState["Sorting"] != null)
{
return (DataTable)ViewState["Sorting"];
}
else
return null;
}
set
{
ViewState["Sorting"] = value;
}
}
Here, Consider "DTSorting" is the DataTable by which you binds the GridView "gv".
protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["SortedTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
gridUsers.DataSource = Session["SortTable"];
gridUsers.DataBind();
}
}
Adapted from this msdn example:

Sorting GridView Formed With Data Set

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>

Resources