i want to findcontrol of Footertemplate in DataGrid Asp . But it return null . Can you help me .
<asp:DataGrid ID="dtgDSSP" runat="server" AutoGenerateColumns="false" OnItemDataBound="dtgDSSP_ItemDataBound"
ShowFooter="true" onselectedindexchanged="dtgDSSP_SelectedIndexChanged">
<Columns>
<asp:TemplateColumn HeaderText="Sản Phẩm">
<ItemTemplate>
<asp:HiddenField ID="HidIDSP" runat="server" />
<asp:DropDownList ID="dropSanPham" runat="server">
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="dropSPAdd" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateColumn>
Code behind :
protected void dtgDSSP_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropAdd;
int footerIndex = dtgDSSP.Controls[0].Controls.Count - 1;
dropAdd = dtgDSSP.Controls[0].Controls[footerIndex].FindControl("dropSPAdd") as DropDownList;
if (dropAdd != null)
{
dropAdd.DataSource = Constant.dictSanPham;
dropAdd.DataValueField = "key";
dropAdd.DataTextField = "value";
dropAdd.DataBind();
}
}
Get Footer dropSPAdd control with below syntex:
dtgDSSP.Controls[0].Controls[dtgDSSP.Controls[0].Controls.Count - 1].Controls[0].FindControl("dropSPAdd") as DropDownList
So Check below code
Html :-
<asp:DataGrid ID="dtgDSSP" runat="server" AutoGenerateColumns="false" OnItemDataBound="dtgDSSP_ItemDataBound"
ShowFooter="true" OnSelectedIndexChanged="dtgDSSP_SelectedIndexChanged">
<Columns>
<asp:TemplateColumn HeaderText="Sản Phẩm">
<ItemTemplate>
<asp:HiddenField ID="HidIDSP" runat="server" />
<asp:DropDownList ID="dropSanPham" runat="server">
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="dropSPAdd" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateColumn>
<asp:ButtonColumn Text="Select" CommandName="Select"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
Code Behind:-
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
System.Data.DataTable dtobj = new System.Data.DataTable();
dtobj.Columns.Add("Test");
dtobj.Rows.Add();
dtobj.Rows[dtobj.Rows.Count - 1]["Test"] = "Testimg";
dtobj.Rows.Add();
dtobj.Rows[dtobj.Rows.Count - 1]["Test"] = "Testimg111";
dtgDSSP.DataSource = dtobj;
dtgDSSP.DataBind();
}
}
protected void dtgDSSP_SelectedIndexChanged(object sender, EventArgs e)
{
var dropAdd = dtgDSSP.Controls[dtgDSSP.Controls.Count - 1].Controls[dtgDSSP.Controls[0].Controls.Count - 1].Controls[0].FindControl("dropSPAdd") as DropDownList;
if (dropAdd != null)
{
dropAdd.DataSource = Constant.dictSanPham;
dropAdd.DataValueField = "key";
dropAdd.DataTextField = "value";
dropAdd.DataBind();
}
}
protected void dtgDSSP_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
var dropAdd = e.Item.Controls[0].FindControl("dropSPAdd") as DropDownList;
if (dropAdd != null)
{
dropAdd.DataSource = Constant.dictSanPham;
dropAdd.DataValueField = "key";
dropAdd.DataTextField = "value";
dropAdd.DataBind();
}
}
}
Related
data is retrieved from the attendance table and the column name is status I want to change the status of the employee to 'leave' if the status of employee is other than 'present' and 'absent'
MY aspx design code
<asp:DropDownList ID="ddlStatus" runat="server" DataValueField="<%# statusConversion(Eval("Status")) %>">
<asp:ListItem value="Present" Text = "Present"></asp:ListItem>
<asp:ListItem value="Absent" Text="Absent"></asp:ListItem>
<asp:ListItem value="Leave" Text="Leave"></asp:ListItem>
</asp:DropDownList>ode here
MY C# backend function code
public String statusConversion(object myVal)
{
String p = "Present";
String a = "Absent";
String l = "Leave";
String val = myVal.ToString();
if (val.Equals(a) || val.Equals(p))
{
return val;
}
else
{
val = l;
return val;
}
}
According to your description, I suggest you could use gridview row databound method to achieve your requirement. You could set the dropdown’s select value in this method and use your custom method to check the stauts codes.
More details, you could refer to below codes:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="GridviewWithDDL.aspx.cs" Inherits="WebFormIdentityTest.GridviewWithDDL" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false" OnDataBound="GridView1_DataBound" >
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width="30" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Operation">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("Status") %>'/>
<asp:DropDownList ID="ddlStatus" runat="server" >
<asp:ListItem value="Present" Text = "Present"></asp:ListItem>
<asp:ListItem value="Absent" Text="Absent"></asp:ListItem>
<asp:ListItem value="Leave" Text="Leave"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Code-behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormIdentityTest
{
public partial class GridviewWithDDL : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable d1 = new DataTable();
d1.Columns.Add("id");
d1.Columns.Add("Status");
d1.Columns.Add("SelectSource");
d1.Columns.Add("SourceName");
d1.Rows.Add("1", "Present", "bbbb", "aaaaaaa");
d1.Rows.Add("2", "Absent", "ccccc", "dddddd");
d1.Rows.Add("3", "Leave", "dddd", "fffff");
d1.Rows.Add("4", "aaaa", "eeee", "ffff");
d1.Rows.Add("5", "Leave", "cccc", "asdasdas");
d1.Rows.Add("6", "bbb", "werwer", "qweqwe");
GridView1.DataSource = d1;
GridView1.DataBind();
}
public static String statusConversion(object myVal)
{
String p = "Present";
String a = "Absent";
String l = "Leave";
String val = myVal.ToString();
if (val.Equals(a) || val.Equals(p))
{
return val;
}
else
{
val = l;
return val;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = gvRow.FindControl("ddlStatus") as DropDownList;
HiddenField hf = gvRow.FindControl("HiddenField1") as HiddenField;
ddl.SelectedValue = statusConversion(hf.Value);
}
}
}
}
}
Result:
i am stuck in a situation where i need to add pagination to parent gridview only(I have a nested gridview where i don't want to add paginatiion to child gridview).i have searched for many example but however I couldn't find any solution.Please help me with this. I am stuck on this issue and could not find any workaround.i am getting input string was not in correct format error on rowcommand event on line
int id = int.Parse(e.CommandName.ToString());
<asp:GridView ID="GVLeader" runat="server" AutoGenerateColumns="false"
DataKeyNames="id" OnRowCommand="GVLeader_RowCommand"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "15" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Eval("Name") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Detail View" ControlStyle-
BackColor="#EBEBEB">
<ItemTemplate>
<asp:Button runat="server" ID="btnplus" Text="Edit Details"
CssClass="greenButton" CommandName='<%#Eval("id") %>'
CommandArgument='<%#Container.DataItemIndex%>' />
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Salary" >
<ItemTemplate>
<asp:Label ID="lblEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Address " >
<ItemTemplate>
<asp:Label ID="lblEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind Code:-
namespace Final
{
public partial class test : System.Web.UI.Page
{
SqlConnection con = new
SqlConnection(ConfigurationSettings.AppSettings["server"].ToString());
SqlConnection con1 = new SqlConnection("confidential"); //Create
sqlconnection
SqlDataAdapter da;
DataTable dt2, dt1;
Properties objlog = new Properties();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGVLeader();
}
}
protected void GVLeader_RowCommand(object sender,
GridViewCommandEventArgs e)
{
int id = int.Parse(e.CommandName.ToString());
int rowindex = int.Parse(e.CommandArgument.ToString());
GridView GVMember =
(GridView)GVLeader.Rows[rowindex].FindControl("GVMember");
Button btn =
((Button)GVLeader.Rows[rowindex].FindControl("btnplus"));
if (btn.Text == "Edit Details")
{
btn.Text = "Cancel";
GVMember.DataSource = LoadGVMember(id);
GVMember.DataBind();
GVMember.Visible = true;
}
else
{
btn.Text = "Edit Details";
GVMember.Visible = false;
}
}
public void LoadGVLeader()
{
da = new SqlDataAdapter("select * from emptable", con);
dt = new DataTable();
da.Fill(dt);
GVLeader.DataSource = dt;
GVLeader.DataBind();
}
protected DataTable LoadGVMember(int id)
{
da = new SqlDataAdapter("select * from emptable where ID=" + id,
con);
dt1 = new DataTable();
da.Fill(dt1);
ViewState["dt"] = dt1;
return dt1;
}
protected void GVMember_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = e.NewEditIndex;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
int id1 = int.Parse(Gv.DataKeys[e.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
Label lbldeleteid = (Label)gvrow.FindControl("lblID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM emptable where ID='" +
Convert.ToInt32(GVLeader.DataKeys[e.RowIndex].Value.ToString()) + "'",
con);
cmd.ExecuteNonQuery();
con.Close();
LoadGVLeader();
}
}
}
remove pagination props from child grid(GVMember)
change
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
with
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" AlternatingRowStyle-
CssClass="alt" AllowSorting="true">
I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
Hi I have a GridView control and in it a TextBox control inside an EditItemTemplate Field.
Now I need to change the textbox text when the user enters the edit mode.
When I run the program the textbox will take the value of the label that was in the ItemTemplate and I cant access the textbox.
.aspx:
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel"
onrowupdating="GridView1_RowUpdating" onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound" DataKeyNames="TweetID">
<Columns>
<asp:TemplateField HeaderText="ProfilePicture">
<ItemTemplate>
<asp:ImageButton ID="ProfileImage" runat="server" CommandName="Redirect"
CommandArgument='<%# Container.DataItemIndex %>' Height="40px" Width="40px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FullName">
<ItemTemplate>
<asp:label ID="FullNameLabel" runat="server" text='<%#Eval("FullName") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="UserNameLabel" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<%--<asp:Label ID="TweetLabel" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>--%>
<asp:Label ID="TweetLabel" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TweetTB" runat="server" Text='<%#Eval("TweetText") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="TweetPic" runat="server"
ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' Height="125px" Width="222px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:ImageButton ID="ReTweetImgBTN" runat="server"
ImageUrl="~/SrcImage/retweet-action.png" Height="27px" Width="29px"
CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Label ID="ReTweetEd" runat="server" Text="ReTweetEd" Visible="false"></asp:Label>--%>
<%--<asp:Button ID="ReTweetBTN" runat="server" Text="ReTweet" CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />--%>
<asp:Label ID="ReTweetStat" runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
<asp:ImageButton ID="LikeImgBTN" runat="server" ImageUrl="~/SrcImage/like-action.png"
Height="27px" Width="29px" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Button ID="LikeBTN" runat="server" Text="Like" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />--%>
<asp:Label ID="LikeStat" runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TweetID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="TweetID" runat="server" Value='<%#Eval("TweetID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="UserID" runat="server" Value='<%#Eval("UserID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
Session["UserID"] = 1; // To be removed
if(!IsPostBack)
BindGridview();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
if (e.CommandName == "Like")
{
int index = Convert.ToInt32(e.CommandArgument);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
LikeHelper.Like(tweetID, userId);
}
else
LikeHelper.Like(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
}
if (e.CommandName == "ReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
ReTweetHelper.ReTweet(tweetID, userId);
}
else
ReTweetHelper.ReTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
}
if (e.CommandName == "UnReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
int RetweetID = ReTweetHelper.GetReTweetIdFromReTweetByUserIdAndTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
int TweetID = NewTweetHelper.GetTweetIdFromTweetByReTweetId(RetweetID);
ReTweetHelper.RemoveReTweet(RetweetID);
NewTweetHelper.GeneralRemoveTweet(TweetID);
}
if (e.CommandName == "Redirect")
{
int index = Convert.ToInt32(e.CommandArgument);
int TweetID = int.Parse(GridView1.DataKeys[index].Value.ToString());
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(TweetID))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(TweetID);
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
int UserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(UserID));
}
else
Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(NewTweetHelper.GetUserIdFromTweetByTweetId(TweetID)));
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
//TextBox TextBox = GridView1.Rows[e.NewEditIndex].FindControl("TweetTB") as TextBox;
//HiddenField TweetID = GridView1.Rows[e.NewEditIndex].FindControl("TweetID") as HiddenField;
//TextBox.Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(TweetID.Value.ToString())).TweetText;
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataBind();
}
public void BindGridview()
{
int userId = int.Parse(Session["UserID"].ToString());
ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
DataSet ds = objWs.SelectTweets(userId, 0);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
int index = Convert.ToInt32(e.RowIndex);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int RetweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
ReTweetHelper.RemoveReTweet(RetweetID);
NewTweetHelper.GeneralRemoveTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()));
}
else
NewTweetHelper.GeneralRemoveTweet(Convert.ToInt32(GridView1.DataKeys[index].Value.ToString()));
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField userIdLbl = (HiddenField)e.Row.FindControl("UserID");
HiddenField tweetid = (HiddenField)e.Row.FindControl("TweetID");
LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
editBt.Visible = userId == Convert.ToInt32(userIdLbl.Value);
ImageButton ProfileImage = e.Row.FindControl("ProfileImage") as ImageButton;
ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(int.Parse(userIdLbl.Value.ToString()));
// if retweet
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
Tweet tweet = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
string FullName = UserHelper.GetName(tweet.UserID);
// change tweet
Label name = e.Row.FindControl("FullNameLabel") as Label;
Label UserName = e.Row.FindControl("UserNameLabel") as Label;
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
int RealUserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
name.Text = "Retweeted by " + FullName + "<br>" + UserHelper.GetName(RealUserID);
UserName.Text = UserHelper.GetUserName(RealUserID);
ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(RealUserID);
editBt.Visible = false;
}
//if there is image
Image img = (Image)e.Row.FindControl("TweetPic");
img.Visible = img.ImageUrl != "~/UploadedImages/";
//stats
Label LikeStat = e.Row.FindControl("LikeStat") as Label;
Label ReTweetStat = e.Row.FindControl("ReTweetStat") as Label;
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(RealTweetID).ToString();
if (int.Parse(LikeStat.Text.ToString()) > 0)
LikeStat.Visible = true;
ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(RealTweetID).ToString();
if (int.Parse(ReTweetStat.Text.ToString()) > 0)
ReTweetStat.Visible = true;
}
else
{
LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(int.Parse(tweetid.Value.ToString())).ToString();
if (int.Parse(LikeStat.Text.ToString()) > 0)
LikeStat.Visible = true;
ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(int.Parse(tweetid.Value.ToString())).ToString();
if (int.Parse(ReTweetStat.Text.ToString()) > 0)
ReTweetStat.Visible = true;
}
// retweeted
if (ReTweetHelper.IsReTweetExistByUserIdAndTweetId(userId,int.Parse(tweetid.Value.ToString())))
{
ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
Retweet.ImageUrl = "~/SrcImage/retweet-action-on.png";
Retweet.CommandName = "UnReTweet";
}
if (NewTweetHelper.IsTweetByUser(int.Parse(tweetid.Value.ToString()), userId))
{
ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
Retweet.ImageUrl = "~/SrcImage/retweet-action-inactive.png";
Retweet.CommandName = null;
}
//Like Button
ImageButton LikeImg = e.Row.FindControl("LikeImgBTN") as ImageButton;
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
if(LikeHelper.IsUserLikeTweet(userId,RealTweetID))
LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
}
else
{
if (LikeHelper.IsUserLikeTweet(userId,int.Parse(tweetid.Value.ToString())))
LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
}
//Hyper Link Text
Label TweetLabel = (Label)e.Row.FindControl("TweetLabel");
//TextBox TweetTB = (TextBox)e.Row.FindControl("TweetTB");
Tweet TweetText = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
//TweetTB.Text = "a";// TweetText.TweetText.ToString();
string text = NewTweetHelper.HyperLinkTweet(int.Parse(tweetid.Value.ToString()));
//TweetText.TweetText= text; //need?
TweetLabel.Text = text;
//Change Tb in edit cand do it in RowEditting
//if (e.Row.RowState == DataControlRowState.Edit)
//{
// TextBox TextBox = e.Row.FindControl("TweetTB") as TextBox;
// Tweet Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
// TextBox.Text = "abc";
//}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
HiddenField TweetID = GridView1.Rows[e.RowIndex].FindControl("TweetID") as HiddenField;
TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("TweetTB") as TextBox;
NewTweetHelper.UpdateTweet(int.Parse(TweetID.Value), TweetText.Text);
GridView1.EditIndex = -1;
BindGridview();
}
In the RowEditing event, you can set the EditIndex value and re-bind the data to the GridView:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
Then, in the RowDataBound event, you can access the controls of the row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == GridView1.EditIndex)
{
TextBox txtBox = e.Row.FindControl("TweetTB") as TextBox;
...
}
else
{
...
}
}
I have created gridview with paging and search a data within gridview.I have number of data and number of page if u filter data in gridview it successfully display result with paging. After display i will click on next page because gridview will display only 10 records per page but i have more than 10 records which i have filtered so it will display page wise. Then when i click next page gridview will loads whole data from database and display but i want display only filtered record while searching data.
the aspx code is below
<asp:Button ID="Search" Text="Search" runat="server" CssClass="searchbtn" OnClick="Search_Click" />
<asp:GridView ID="gvEdit" runat="server" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="10" OnRowCommand="gvEdit_RowCommand">
<HeaderStyle HorizontalAlign="Center" BackColor="#2D96CE" ForeColor="White" />
<AlternatingRowStyle BackColor="#D4EFFD" />
<PagerSettings Position="Top" />
<PagerStyle Height="8px" HorizontalAlign="Center" />
<PagerTemplate>
<table align="center" style="width: 100%;" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="center" style="width: 60%;">
<table align="center" width="50%">
<tr>
<td>
<asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
</td>
<td style=" width: 8%;">
<asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
<asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="200px" />
<asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="11%" />
<asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-Width="19%" />
<asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-Width="13%" />
<asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-Width="200px" />
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="" HeaderText="Schedule1" ItemStyle-Width="6.9%">
<ItemTemplate>
<a href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
<img src="<%#Eval("schedule1") %>" alt="" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Copy">
<ItemTemplate>
<asp:ImageButton ID="lnkDuplicate" runat="server"
ImageUrl="~/Images/grid/file_duplicate 35x35.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Edit" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="lnkBtnContinue" runat="server"
ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDel" runat="server"
ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and aspx.cs code is below
protected void Search_Click(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
try
{
if (txtsearch.Text != "")
{
if (ViewState["data"] != null)
{
DataTable dt = (DataTable)ViewState["data"];
DataView dv = new DataView(dt);
dv.RowFilter = "ref_no Like '%" + txtsearch.Text + "%' OR fum Like '%" + txtsearch.Text + "%' OR filing_type Like '%" + txtsearch.Text + "%'OR business_name Like '%" + txtsearch.Text + "%'OR filing_status Like '%" + txtsearch.Text + "%'";
ViewState["filter"] = dv;
gvEdit.DataSource = dv;
gvEdit.DataBind();
//gvformlist.DataSource = dv;
//gvformlist.DataBind();
}
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
protected void Reset_Click(object sender, EventArgs e)
{
txtsearch.Text = "";
gvEdit.DataSource = ViewState["data"];
gvEdit.DataBind();
//gvformlist.DataSource = ViewState["data"];
//gvformlist.DataBind();
}
protected void gvformlist_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//gvEdit.PageIndex = e.NewPageIndex;
//gvformlist.PageIndex = e.NewPageIndex;
LoadFormList();
}
protected void gvformlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow pagerRow = gvEdit.TopPagerRow;
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (e.Row.RowType == DataControlRowType.Pager)
{
pageLabel.Text = "Page " + (gvEdit.PageIndex + 1) + " of " + gvEdit.PageCount;
}
}
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, string DDlPager)
{
// to Get No of pages and Page Navigation
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
ImageButton btnFirst = (ImageButton)gvPagerRow.FindControl("ImgeBtnFirst");
ImageButton btnPrevious = (ImageButton)gvPagerRow.FindControl("ImgbtnPrevious");
ImageButton btnNext = (ImageButton)gvPagerRow.FindControl("ImgbtnNext");
ImageButton btnLast = (ImageButton)gvPagerRow.FindControl("ImgbtnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DDlPager);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
string strPgeIndx = Convert.ToString(gridView.PageIndex + 1) + " of "
+ gridView.PageCount.ToString();
Label lblpageindx = (Label)gvPagerRow.FindControl("lblpageindx");
lblpageindx.Text += strPgeIndx;
}
protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
{
gvEdit.PageIndex = ((DropDownList)sender).SelectedIndex;
LoadFormList();
}
protected void gvEdit_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(gvEdit, e.Row, this, "ddlPageSelector");
}
}
protected void gvEdit_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
I have changed code in gvEdit_PageIndexChanging as per someone suggestion code is below
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (ViewState["filter"] != null)
{
gvEdit.PageIndex = e.NewPageIndex;
gvEdit.DataSource = ViewState["filter"];
gvEdit.DataBind();
}
else
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
after that i run the code and i am getting error
error is System.Runtime.Serialization.SerializationException: Type 'System.Data.DataView' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
According to your question I try to give an answer. If you find my answer useful then mark is as answer or vote it up.
What I have done in below code is when user click on search button without input any student name it shows per page 10 records of all students and if you search by name it shows only specific students with paging. In below code I use a stored procedure and in that I put three parameters such as following:
#startRowIndex int
#pageSize int
#studentname varchar(50) = NULL
Default.aspx markup:
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<tr>
<td>Gridview Pagging</td>
</tr>
<tr>
<td>
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div>
<asp:GridView ID="gv" runat="server" Width="100%" EmptyDataText="No Data Found!"
ShowFooter="False" AutoGenerateColumns="False" SkinID="WithOutPaging" GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="Studentname" HeaderText="Student Names"></asp:BoundField>
<asp:BoundField DataField="Studentage" HeaderText="Age"></asp:BoundField>
</Columns>
<EmptyDataRowStyle CssClass="emptyrow" />
<HeaderStyle CssClass="headerstyle2" />
<FooterStyle CssClass="footerstyle"></FooterStyle>
<EditRowStyle CssClass="editrowstyle"></EditRowStyle>
<SelectedRowStyle CssClass="selectedrowstyle"></SelectedRowStyle>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></PagerStyle>
</asp:GridView>
</div>
<div style="margin-top: 20px; margin-bottom: 70px;" align="center">
<asp:Button ID="btnFirst" runat="server" Text="First" CommandName="First" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnPrevious" runat="server" Text="Previous" CommandName="Previous"
OnCommand="ChangePage" Visible="False" />
<asp:Button ID="btnNext" runat="server" Text="Next" CommandName="Next" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnLast" runat="server" Text="Last" CommandName="Last" OnCommand="ChangePage"
Visible="False" />
<br />
<br />
<asp:Label ID="lblPageText1" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> Page </asp:Label>
<asp:Label ID="lblCurrentPage" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
<asp:Label ID="lblPageText2" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> of </asp:Label>
<asp:Label ID="lbltotalPages" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Default.aspx.cs code:
#region "Declaration"
private int pageSize = 10;
SqlConnection con;
string conquery = "Data Source=.;Initial Catalog=GridviewPagging;User ID=sa;Password = 123";
#endregion
#region "Events"
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["startRowIndex"] = 0;
ViewState["currentPageNumber"] = 0;
}
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
ViewState["currentPageNumber"] = 1;
ViewState["startRowIndex"] = 0;
break;
case "Previous":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) - 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) - pageSize;
break;
case "Next":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) + 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) + pageSize;
break;
case "Last":
ViewState["startRowIndex"] = pageSize * (Int32.Parse(lbltotalPages.Text) - 1);
ViewState["currentPageNumber"] = lbltotalPages.Text;
break;
}
this.fillgridview();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
fillgridview();
}
#endregion
#region "Methods"
private DataSet ds(int RowIndex, int Pagesize, string studentname)
{
DataSet dataset;
try
{
con = new SqlConnection(conquery);
SqlCommand cmd = new SqlCommand("SP_GET_STUDENT_DATA", con);
cmd.Parameters.AddWithValue("#startRowIndex", RowIndex);
cmd.Parameters.AddWithValue("#pageSize", Pagesize);
cmd.Parameters.AddWithValue("#studentname", studentname);
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
dataset = new DataSet();
da.Fill(dataset);
}
return dataset;
}
catch (SqlException ex)
{
return dataset = null;
}
}
private void fillgridview()
{
DataSet newds = ds(Convert.ToInt32(ViewState["startRowIndex"].ToString()), pageSize, searchbox.Text.Trim());
if (newds.Tables.Count == 0)
{
return;
}
else
{
btnFirst.Visible = true;
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
lblCurrentPage.Visible = true;
lbltotalPages.Visible = true;
lblPageText1.Visible = true;
lblPageText2.Visible = true;
ViewState["TotalRows"] = newds.Tables[1].Rows[0][0];
newds.Tables[1].Rows.Clear();
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 0)
{
ViewState["currentPageNumber"] = 1;
}
setPages();
this.gv.Visible = true;
this.gv.DataSource = newds.Tables[0];
this.gv.DataBind();
}
}
private void setPages()
{
lbltotalPages.Text = "";
lblCurrentPage.Text = "";
try
{
lbltotalPages.Text = CalculateTotalPages(Convert.ToDouble(ViewState["TotalRows"])).ToString();
lblCurrentPage.Text = (ViewState["currentPageNumber"] == null ? "0" : ViewState["currentPageNumber"].ToString());
if (Int32.Parse(lblCurrentPage.Text) == 0 | Int32.Parse(lbltotalPages.Text) == 0)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
else
{
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 1)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
if (int.Parse(lbltotalPages.Text) > 0)
{
this.btnNext.Enabled = true;
this.btnLast.Enabled = true;
}
else
{
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
}
if (Convert.ToInt32(ViewState["currentPageNumber"]) == int.Parse(lbltotalPages.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
}
catch (Exception ex)
{
}
}
private int CalculateTotalPages(double totalrows)
{
return Convert.ToInt32(Math.Ceiling(totalrows / pageSize));
}
#endregion
first set enablepagingandcallback = false in gridview , then add
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1; //it is the datasource with filtered query which does the work
GridView1.DataBind();
}