I asked a similar question to this but the circumstances have changed.
I bind my gridview through code rather than on the source.
The pagination works fine, but if I click a button on second page of the gridview (after pagination), the postback is causing the pagination to reset to page 1. Can anyone tell me what I'm doing wrong?
Within my pageload i have set the !POSTBACK method as shown i.e if there is postback event, then it shouldn't reset the grid but it does!
Heres the onload:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
else
{
GridView1.Columns[10].Visible = false;
GridView1.Columns[11].Visible = false;
}
if (!IsPostBack)
{
BindGrid();
}
The BindGrid();
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmd = new SqlCommand("select * from Coffees ORDER BY coffeeName ASC", sqlcon);
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Page index method:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
You need to bind your gridview in GridView1_PageIndexChanging event
GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
BindGrid();
}
hopefully it works for you.
Since you are binding grid view dynamically, Please remove
if (!IsPostBack)
condition from page load. Grid view needs binding every time.
I found this issue. I forgot that after I add an item to my cart i was calling response.redirect to refresh the page....obviously this meant the page was recalled refreshing the page so the grid was always going to reset. Thanks again.
Related
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
public void GetData()
{
string SQL=string.Empty;
SqlDataAdapter commandToBeLog=null;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SQL = " SELECT * FROM tbl_Video";
if (txtSearchVideo.Text.Trim() != string.Empty)
{
SQL += " WHERE VideoName LIKE #VideoName ";
ListView1.DataSource = null;
}
SQL += " ORDER BY VideoID DESC";
DataSet ds = new DataSet();
SqlDataAdapter myCommand = new SqlDataAdapter(
SQL, con);
if (txtSearchVideo.Text.Trim() != string.Empty)
{
myCommand.SelectCommand.Parameters.Add("#VideoName", SqlDbType.NVarChar, 300).Value = "%" + txtSearchVideo.Text + "%";
}
myCommand.Fill(ds);
ListView1.DataSource = ds;
ListView1.DataBind();
}
protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
this.GetData();
}
protected void btnSerch_Click(object sender, EventArgs e)
{
if (txtSearchVideo.Text.Trim() != string.Empty)
{
GetData();
GetData();
}
else
{
GetData();
}
}
Hi, how do i make the list view paging is no depedent to the textbox search. I got a problem with listview search pager, whenever I click search button with textbox value equal to A, the btnSerch_Click event fire. It show out 3 pages data with results and then I navigate to page 3. But when I type in the textbox with value B(it suppose show one page data), and I didnt click search button, but i go to click page 2. The weird thing happen, it show not relevant data or broken data.
How do i solve this problem, i don't want the page navigate bar depedent to the textbox. What I mean is I click page 2, the GetData() fucntion not fire, but just the page trigger only.
You need to to remove this line
ListView1.DataSource = null;
from the GetData method. Because if you null the ListView, the properties you set in ListView1_PagePropertiesChanging will be lost.
And you can reduce the Button click method to just one line.
protected void btnSerch_Click(object sender, EventArgs e)
{
GetData();
}
I have 3 gridviews in 3 different updatepanels, which i update them after RowCommand.
GridView1.DataBind();
GridView2.DataBind();
GridView3.DataBind();
The weird thing is only GridView1_RowCommand can update all three gridview. GridView2_RowCommand using the same method but i cannot update the gridview.
Please help me.
Thanks in advance.
Here is the code for Rowcommand:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//check the commandName
if (e.CommandName != "SaveStartTime")
return;
int rowIndex = int.Parse(e.CommandArgument.ToString());
string id = GridView1.Rows[rowIndex].Cells[0].Text;
Label time = GridView1.Rows[rowIndex].Cells[4].FindControl("ActualTimeStart") as Label;
time.Text = DateTime.Now.ToString("HH:mm");
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = "Server=.\\SqlExpress;Database=CMOS;Trusted_Connection=True";
Cn.Open();
var Cm = Cn.CreateCommand();
string store = string.Format(#"UPDATE [ApprovedExitPass] SET ActualTimeStart = '{0}' WHERE Id='{1}'", time.Text, id);
SqlCommand cmd = new SqlCommand(store, Cn);
cmd.Parameters.AddWithValue("#ActualTimeStart", time.Text);
cmd.ExecuteNonQuery();
Cn.Close();
GridView1.DataBind();
GridView2.DataBind();
GridView3.DataBind();
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
//check the commandName
if (e.CommandName != "SaveReturnTime")
return;
int rowIndex = int.Parse(e.CommandArgument.ToString());
string id = GridView2.Rows[rowIndex].Cells[0].Text;
Response.Write(id);
Label time = GridView2.Rows[rowIndex].Cells[4].FindControl("ActualTimeArrive") as Label;
time.Text = DateTime.Now.ToString("HH:mm");
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = "Server=.\\SqlExpress;Database=CMOS;Trusted_Connection=True";
Cn.Open();
var Cm = Cn.CreateCommand();
string store = string.Format(#"UPDATE [ApprovedExitPass] SET ActualTimeArrive = '{0}' WHERE Id='{1}'", time.Text, id);
SqlCommand cmd = new SqlCommand(store, Cn);
cmd.Parameters.AddWithValue("#ActualTimeArrive", time.Text);
cmd.ExecuteNonQuery();
Cn.Close();
GridView1.DataBind();
GridView2.DataBind();
GridView3.DataBind();
}
YES,gridview1_rowcommand will update all three because if you see the gridview1_rowcommand.in that method you are calling the databind of other two gridviews also . so now why this happening only while calling gridview1_rowcommand because you might be probably calling first grid row command or some other Issue.
SO probably Verify whether you getting value in Response.write(id)
When trying to update GridView data, it successfully runs, but it gets the old data instead of the data you type in the textboxes.
This is what I have:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
GridView1.DataBind();
}
and
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
and
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
}
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
For example, the current data is:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
I type in new data:
name: John, phone: 555-555-5555, email: test2#test2.com, contactId: 22
Data that ends up in the database:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
}
Every time the page posts back you are rebinding the grid. Move the binding of the grid into a separate function. After you do the row updating, rebind the grid.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
BindGrid();
}
When you edit you must call BindGrid too.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//GridView1.DataBind(); this is meaningless, you have not set a DataSource
BindGrid();
}
When you raise the RowUpdating event your basically getting the values BEFORE the GridView updates the row. This is basically so you can cancel the update operation. To get what you've type in I think you need to get the new values (the Dictionary e.NewValues() in your case).
In your case you can use it something like this (assuming name, phone and email are what they're called in your gridview):
foreach(DictionaryEntry de in e.NewValues())
{
string name = de.FirstOrDefault(x => x.Key == "name").Value;
string phone = de.FirstOrDefault(x => x.Key == "phone").Value;
string email = de.FirstOrDefault(x => x.Key == "email").Value;
}
NOTE: If you're simply using this to get the values typed in to update your database then you're better of binding the datagrid and use the value after that to ensure you definitely have the same values in the datagrid as to what you put into the database. Alternatively, use the RowUpdated event instead of the RowUpdating event.
The most prevalent reason is that we usually forgot to check the postbacks in the Page Load event.
check the post-back, then the problem will be removed.
if (! IsPostBack)
{
readData();
...
}
Prokzy I have just your example on my side and doing something like this worked fine for me. notice the DataSource portion. I have a DataSet instantiated as aDataSet btw
protected void GridView1_GridViewPageEventArgs e(object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
GridView1.DataSource = null;
GridView1.DataSource = aDataset;
GridView1.DataBind();
}
You need to call LoadContacts again and reassign GridView1.DataSource after the database is updated. Currently, the DataSource is not being updated - and is just using the collection that was retrieved prior to the row update.
I have a problem related to DataTable in .net.
i am trying to fill datatable on page_load .that part is ok no issue datatable correctly filled up with data. but I noticed that when I clicked button on page... it again try to fill datatable which just a time-consuming task... I want datatable should fill once only ,when , when site open in browser .. not at every click ... because I have a large amount of data in table so it takes time to load in datatable..
plz help me out ...
here is my code:
protectd void Page_Load(object sender, EventArgs e)
{
cnn.ConnectionString= ConfigurationManager.ConnectionStrings["con"].ConnectionString;
// if (this.IsPostBack == true)
{
dr1 = TableUtoP();
dtWordsList.Load(dr1);
}
}
OleDbDataReader TableUtoPunj(String ArrWord)
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
}
cnn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "SELECT U, P from UtoP";
cmd.Connection = cnn;
OleDbDataReader dr = cmd.ExecuteReader();
return dr;
}
You need to check if the page is posting back or not, like this:
protected void Page_Load(object sender, EventArgs e)
{
cnn.ConnectionString= ConfigurationManager.ConnectionStrings["con"].ConnectionString;
if(!IsPostBack)
{
// This will only happen when the page is first loaded, as the first time is not considered a post back, but all others are
dr1 = TableUtoP();
dtWordsList.Load(dr1);
}
}
Only fill the dataTable if it's not a PostBack...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//TO DO: Make the call to fill the data table here
}
}
I am working on my first web project and I need help adding IF logic when using GridView. I have a page (CustomerListPage) that has a GridView item that displays a list of customers(rows) that can be clicked. Once the customer is clicked, the user is redirected to a page called "CustomerUsagePage" which shows the most recent record of this customer. This is what my GridView code looks like for my CustomerListPage:
if (GridView1.SelectedRow.RowIndex == 0)
{
//string selectedUser = GridView1.SelectedRow.Cells[0].ToString();
Response.Redirect("CustomerUsagePage.aspx?Customer_Name=" );
BindGridview();
}
The code for my CustomerUsagePage looks like this:
private void BindControlvalues()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.CustomerTable", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
Label4.Text = ds.Tables[0].Rows[0][1].ToString();
Label1.Text = ds.Tables[0].Rows[0][0].ToString();
Label2.Text = ds.Tables[0].Rows[0][3].ToString();
Label3.Text = ds.Tables[0].Rows[0][4].ToString();
}
My problem is that I can only add IF logic the page where my GridView is located. I would like to click on a customer and have his data appear on my CustomerUsagePage with an if statement. Is it possible? I know I can do this by adding a page per customer but I dont want to go down that route, it seems to tedious. Does anyone have any suggestions?
You can use GridView-FormView (Master/Detail) Control
Link : http://www.codeproject.com/Articles/16780/GridView-FormView-Master-Detail-Control.
Or you can use classic behavior with ItemCommand event
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = CustomersGridView.Rows[index];
.....//Adjust your Response
}
}