Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Saturday, March 27, 2010

Gridview sorting,paging

//Take one Grid View and Bind all the column through
//hdnSort is a Hidden field take one hidden field also.
asp:TemplateField
ItemTemplate and give the sort expression also and paging and sorting also true the property of GridView...

//Web.config file
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>

//in aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData(string sorting)
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{

}


sql = "Select student_id,last_name,first_name,Score from Student order by " + sorting;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);

if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();

if (ds.Tables.Count == 0)
{

//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }

}

//call Bind Method where you bind the Gridview perform all operation

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData("student_id");

}
}

//for sorting

private string ConvertSortDirectiontoSql(SortDirection sort)
{
string newSortDirection = string.Empty;
switch (sort)
{
case SortDirection.Ascending:
newSortDirection = "Asc";
hdnSort.Value = "Asc";
break;
case SortDirection.Descending:
newSortDirection = "Desc";
hdnSort.Value = "Desc";
break;
}
return newSortDirection;

}



protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//hdnSort is a Hidden field take one hidden field also.
if (hdnSort.Value.Length == 0 || hdnSort.Value == "Desc")
e.SortDirection = SortDirection.Ascending;
else
e.SortDirection = SortDirection.Descending;

string sorting = e.SortExpression + " " + ConvertSortDirectiontoSql(e.SortDirection);
if (hdnSort.Value.Length == 0)
hdnSort.Value = "Desc";
bindData(sorting);
}

//for paging

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindData("student_id desc");
}

No comments:

Post a Comment