GridView does not change on page change - c#

Gridview: Data does not change on page change.
Hi, im working on a asp.net website with c#.
I have a gridview with paging, the gridview is populated from an sql database, and on the PageIndexChanging I have:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindGridControl();
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}
If I click on page 2 for example, the next rows of data display fine.
But if I click back to the page 1, the data does not change, it keep displaying the data from the page 2.
How can I solve this?

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
gridView.DataBind();
}
Is your BindGridControl() load the data and set it to your gridView datasource?

You can reverse order of instructions
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
gridView.DataBind();
}

I had this problem too for a long time.
I came up with this and it finally works for me.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindGridControl(e.NewPageIndex);
}
And then in your BindGridControl function:
protected void BindGridControl(int pageNumber = 0)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[connect‌​ion].ConnectionStrin‌​g);
SqlDataReader dr;
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_load";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.PageIndex = pageNumber;
GridView1.DataSource = dt;
GridView1.DataBind();
sqlConn.Close();
}

Try
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
DataBind();
}

Related

GridView bound to Datatable- Paging does not work properly

I have a webform set up with a button click that parses a .txt file and puts it in a datatable. when the parsing ends the datatable is bound to the gridview. I tried to add paging since I get tons of rows but it does not seem to work properly. Whenever I click on the next page the grid disappears and for it to appear again on the correct page I need to click on the button again.
I tried adding the following code to the source :
<asp:GridView ID="GridView1" Runat="server"
AutoGenerateColumns="true"
AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" >
and this bit :
protected void OnPageIndexChanging(object sender, EventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
but it doesn't seem to change anything. Any idea on what I'm doing wrong?
Try to Add OnPageIndexChanging Event inside GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="5">
and your aspx.cs code. Try to Bind Gridview on Page_Load Event.
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{ this.BindGrid();}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * From [dbo].[your table] "))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//here yo have to assign datasource
//Some thing like this
///GridView1.DataSource=DataTable;
GridView1.DataBind();
}

Get more information on GridView row click

I need to get this : When I click on a row, to get a more information about that particular file(every row represents one file from database), and that information is stored in different table... So, how is the best way to do this? Here you have a picture...
public partial class WebForm1 : System.Web.UI.Page
{
Web_service.WebService1SoapClient service;
protected void Page_Load(object sender, EventArgs e)
{
service = new Web_service.WebService1SoapClient();
BindData();
}
protected void BindData()
{
string strConnection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from request", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
r.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
r.Attributes["onmouseout"] = "this.style.textDecoration='none';";
r.ToolTip = "Click to select row";
r.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + r.RowIndex, true);
}
}
base.Render(writer);
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
}
}

search, edit and delete using gridview with sql server in c#

i am using Gridview buttons to edit and delet records from sql DB , the problem that i use specific criteris (search by textbox and combobox) then i do edit for the results here is the code i use :
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["zamzammembersConnectionString"].ConnectionString);
if (!IsPostBack)
{
bind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
public void bind()
{
conn.Open();
SqlCommand com = new SqlCommand("select zam_pcinfo.employe_name as Name , zam_location.locationname as Location from zam_pcinfo inner join zam_location on zam_pcinfo.location_id = zam_location.locationId where zam_pcinfo.employe_name like #name or zam_location.locationname like #locationname;", conn);
com.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = nametxt.Text;
com.Parameters.AddWithValue("#locationname", SqlDbType.VarChar).Value = locationdrop.SelectedValue;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete emp where rowid=" + lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}
}
when i try to make the same code in bind() method to a button it works fine but i couldn't do edit and delete on it . how can i make edit and delete in gridview with data that i search for ?

Using SqlDataAdapter to page a SqlDataReader source

This question seems to be common and I went through this answer already.
Unfortunately, my page still isn't being paged. Here's what my code looks like in C#:
SqlCommand command = new SqlCommand("(SELECT ......", Connection);
SqlDataAdapter myAdapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
myAdapter.Fill(dt);
command.Connection = connection;
command.Connection.Open();
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.AllowPaging = true;
GridView1.PageSize = 15;
command.Connection.Close();
command.Connection.Dispose();
Unfortunately, when I do this, my paging doesn't show up. Am I doing something wrong?
Thanks
Set all of the Paging-related properties before the Databind() method is called. When you use Custom Paging you will have to handle the GridView1_PageIndexChanging event. You need to change the current PageIndex, and re-bind your GridView like this:
void bindGridview()
{
SqlCommand command = new SqlCommand("(SELECT ......", Connection);
SqlDataAdapter myAdapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
myAdapter.Fill(dt);
command.Connection = connection;
command.Connection.Open();
GridView1.AllowPaging = true;
GridView1.PageSize = 15;
GridView1.DataSource = dt;
GridView1.DataBind();
command.Connection.Close();
command.Connection.Dispose();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridview();
}
If you are also binding the GridView on Page_Load, do it like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
bindGridview();
}
You need to add the PageIndexChanging event of GridView to enable paging.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridview();
}

ASP .NET RowUpdating GridView Troubles

I'm having trouble with the RowUpdating Method. My GridView is connected to our local SQL Server, and I'm trying to update the data. Here is the code for the RowUpdating Method from MSDN.
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
I get this error:
System.NullReferenceException: Object reference not set to an instance of an object.
try this code once.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox tname = (TextBox)row.FindControl("nam");
TextBox tques = (TextBox)row.FindControl("que");
MySqlCommand cmd = new MySqlCommand("update exam set name1=#name,ques=#ques where id = #id", con);
cmd.Parameters.Add("#id", MySqlDbType.Int16).Value = id;
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = tname.Text.Trim();
cmd.Parameters.Add("#ques", MySqlDbType.VarChar,40).Value = tques.Text.Trim();
con.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bind();
}
Not all GridViewRow have a DataItem.
You should add a if block around your code and verify the row being updated is of type DataRow.
if (e.Row.RowType == DataControlRowType.DataRow)
{
your code here...
}
More regarding RowTypes : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.rowtype.aspx
public void bindGvEdit()
{
GridView1.DataSource = obj1.SelectAlltbl();
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindGvEdit();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindGvEdit();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
obj1.Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
obj1.Name = ((TextBox)row.Cells[1].Controls[1]).Text;
obj1.Description = ((TextBox)row.Cells[2].Controls[1]).Text;
obj1.Updatetbl();
GridView1.EditIndex = -1;
bindGvEdit();
}

Categories