I have a drop down list with the list items created in the code behind. ddlFill(). Pretty simple and does the job. It's populated with the current month and some months ahead. I use this drop down as a selection to fill a Gridview. When this drop down index changes, it changes a hidden field value and a corresponding query to fill the gridview. All this works as it should. Within the gridview I have another dropdown list and a button. Both submit the selected row to a database. That also works fine. The problem is, each time one of these rows submits to the database, it causes a post back and it resets the whole page. It resets the drop down list to the first list item . I.E. I change the drop down list to index 4 for example. Which would be April in this case. If I submit a row to the db, the page refreshes and goes back to index 0 .. January in this case. How do I keep it from resetting this way and maintaining the position I was in when I submitted the row?
I have tried a few different options. I've tried session states. hidden field value changes. Nothing seems to work. It either does not perform the post back therefore never submits to the db or it does the post back, submits correctly, then resets the whole page. Including resetting the hiddenfield value back to 0
/* This is up in Page load. */
if (Session["pageStatus"] != null)
{
if (Session["pageStatus"].ToString() == "Loaded")
{
hf2.Value = "Loaded";
}
}
else
{
hf2.Value = "New";
}
if (Session["selectedMonth"] != null)
{
hf1.Value = Session["selectedMonth"].ToString();
}
if (ViewState["button_was_clicked"] != null)
{
ddlFill();
StyleDDL();
}
lblTestlabel.Text = hf2.Value;
AddAttributes();
ShowMonth();
if (!Page.IsPostBack)
{
btnReviewCurrentMonth_OnClick(sender, e);
ddlFill();
StyleDDL();
}
private void ddlFill()
{
string a, b, c, d, e, f;
a = "0";
b = "1";
c = "2";
d = "3";
e = "4";
f = "5";
DropDownList1.Items.Insert(0, new ListItem(ReturnMonth(a))); // A blank object call and the ReturnMonth Method fill the list items.
DropDownList1.Items.Insert(1, new ListItem(ReturnMonth(b)));
DropDownList1.Items.Insert(2, new ListItem(ReturnMonth(c)));
DropDownList1.Items.Insert(3, new ListItem(ReturnMonth(d)));
DropDownList1.Items.Insert(4, new ListItem(ReturnMonth(e)));
DropDownList1.Items.Insert(5, new ListItem(ReturnMonth(f)));
/* These were for various testing options to get it to maintain the
state */
hf2.Value = "Loaded";
Session["pageStatus"] = "Loaded";
DropDownList1.SelectedIndex = Int32.Parse(hf1.Value);
}
My goal is to maintain the state of the page after the submission to the db occurs.
I found this question difficult to ask because it had so many moving parts. The ddlFill() method wasn't the problem. All it litterally did was fill list items. Those corresponding Selected Index values would change when selected and based on those values I would assign a different value to a hidden field. Which was then used as SqlDataSource control variable and would bring back GridView data based on that control value.
A drop down list within the gridview was used to select and submit the indexed row to a SQL DB. At the end of that code I was refreshing the page. It needed a refresh to properly submit and bring back a fresh Gridview with the previously submitted row now gone. That was the problem. When it refreshed, it changed the hidden field value to 0 and reset everything back. So, here is what I did.
//This method controls the Drop Down List change event. Underwriter change.
protected void DropDownList1_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
int idx = row.RowIndex;
GridView1.SelectedIndex = idx;
string Client = GridView1.SelectedRow.Cells[0].Text;//Client Name
string NewUw = ddl.Text.ToString();
int UniqCNT = new Int32();
UniqCNT = Int32.Parse(GridView1.SelectedRow.Cells[1].Text.ToString()); //UniqClient */
string ExpPolicyNums = GridView1.SelectedRow.Cells[2].Text;
int Ub = Int32.Parse(GridView1.SelectedRow.Cells[10].Text);//UniqBroker
DateTime ExperationDate = DateTime.Parse(GridView1.SelectedRow.Cells[6].Text); //ExpDate
string Company = GridView1.SelectedRow.Cells[7].Text; //Company issuer
string Broker = GridView1.SelectedRow.Cells[8].Text; //Broker_Name
string Premium = GridView1.SelectedRow.Cells[3].Text; //Premiums
string TotalPremium = GridView1.SelectedRow.Cells[4].Text; //Total premiums
string Reviewed = "No"; //Updates the DB and shows that it hasn't been reviewed by the Message Creator
//DateCreated gets inserted when record is created
string InsertedBy = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(#"\") + 1);
DateTime dateUpDated = DateTime.Now; //Inserts a dateUpdated record
string query = "INSERT INTO [GTU_Apps].[dbo].[Reviewed_Renewal_Policy] (UniqClient, Client, [Expiring_Policies], Premiums, TotalPremium, UniqBroker, ExpDate, NewUw, Company, Broker_Name, Reviewed, DateUpDated, InsertedBy) " +
"VALUES (#UniqCNT, #Client, #ExpPolicyNums, #Premium, #TotalPremium, #Ub, #ExperationDate, #NewUw, #Company, #Broker, #Reviewed, #dateUpDated, #InsertedBy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=GTU_Apps;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqCNT", UniqCNT);
comm.Parameters.AddWithValue("#Client", Client);
comm.Parameters.AddWithValue("#ExpPolicyNums", ExpPolicyNums);
comm.Parameters.AddWithValue("#Premium", Premium);
comm.Parameters.AddWithValue("#TotalPremium", TotalPremium);
comm.Parameters.AddWithValue("#Ub", Ub);
comm.Parameters.AddWithValue("#ExperationDate", ExperationDate);
comm.Parameters.AddWithValue("#NewUw", NewUw);
comm.Parameters.AddWithValue("#Company", Company);
comm.Parameters.AddWithValue("#Broker", Broker);
comm.Parameters.AddWithValue("#Reviewed", Reviewed);
comm.Parameters.AddWithValue("#dateUpDated", dateUpDated);
comm.Parameters.AddWithValue("#InsertedBy", InsertedBy);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
GridView1.DataBind();
GridView1.SelectedIndex = -1;
int index = DropDownList1.SelectedIndex;
ConfirmIndex(index);
//End(sender, e);
}
Using the DataBind worked. It only refreshed the Gridview. Which was really what I needed. I had other items that were refreshing too. That's why those calls below it are there. If someone sees this, hopefully it will help.
For the life of me I cannot seem to figure this out. I have a long DataGridView (that does not allow MultiSelect) and when a user commits a change to the data, the data from the grid is purged and redrawn (because changes can affect multiple rows, this was the simpler approach). However, when I try to select the row programmatically, it does not also fire the DataGridView.SelectionChanged event, which I use to display data from an array which is correlated to the DataGridView current cell index. When doMagicStuff executes, the values for the wrong index (specifically, index 0) is show.
private void doMagicStuff()
{
int selRow = myDGV.CurrentCell.RowIndex;
myDGV.Rows.Clear();
/*Perform Task, Redraw data*/
myDGV.CurrentCell = myDGV[selRow, 0];
}
private void myDGV_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = myDisplayValue1[myDGV.CurrentCell.RowIndex];
Label2.Text = myDisplayValue2[myDGV.CurrentCell.RowIndex];
TextBox1.Text = myEditValue1[myDGV.CurrentCell.RowIndex];
TextBox2.Text = myEditValue2[myDGV.CurrentCell.RowIndex];
}
Make sure that your client settings and OnSelectedIndexChanged is set like so: (ASP.NET AJAX)
.aspx page
<telerik:RadGrid ID="Grid1" runat="server" OnSelectedIndexChanged="Grid1_SelectedIndexChanged" OnItemDataBound="Grid1_ItemDataBound" OnPreRender="Grid1_PreRender">
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true"></Selecting>
</ClientSettings>
</telerik:RadGrid>
aspx.cs page
protected void Grid1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
foreach(GridDataItem item in Grid1.SelectedItems)
{
//column name is in doub quotes
value = item["Name"].Text;
}
}
Add a button click to the form to test the selected values in the DataGridView.. double click that button then paste this code in there
foreach (DataGridViewRow row in myDGV.SelectedRows)
{
Label1.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
Label2.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
TextBox1.Text = row.Cells[0].Value.ToString();//change the 0 or 1 to fit your column Index position
TextBox2.Text = row.Cells[2].Value.ToString();
}
also if you have 4 columns and 4 text boxes then you will assign all of the textbox.Text values within the foreach loop just follow the pattern and increase the index by 1 so 2 textboxes means row.Cells[0] is the first column row.Cells[1] is the second column ...etc
I am using this code to take a gridview count and display in a label on page load and works fine.
Page Load:
int rowCount = dtDetails.Rows.Count;
lblTotalRows.Text = rowCount.ToString() + "records found";
I have a dropdown above my gridview and when I select dropdown values the row count have to changed based on the dropdown selected values.
How could I possibly do that in dropdown selected index change
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtGroup = DataRepository.GetGroup(ddlGroup.Text);
gvDetails.DataSource = dtGroup;
gvDetails.DataBind();
//Now how could I possible show the respective row counts in the label
}
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtDept = DataRepository.GetDept(ddlGroup.Text, ddlDept.Text);
gvDetails.DataSource = dtDept;
gvDetails.DataBind();
//Now how could I possible show the respective row counts of both group and
dept row count since they are cascading dropdowns in the label
}
Any suggestions?
I tend to make a SetData() method so all this kind of code is in one place. So in this instance I would:
protected void SetData(DataTable dtGroup)
{
// Bind the data to the grid
gvDetails.DataSource = dtGroup;
gvODetails.DataBind();
// Show row count
if (!dtGroup.Rows.Count.Equals(0))
lblTotalRows.Text = dtGroup.Rows.Count + " records found";
else
lblTotalRows.Text = "No records found";
}
This way you only have one place that does all the 'bindind' so in your Page_Load you can just call this SetData() method and pass in the datatable, and the same on your SelectedIndexChanged.
I try to refresh page with timer every 1 minute and display data in gridview on next page until last record.
What should I do?
protect void Timer1_Tick(object sender, EventArgs e)
{
if(GridView1.PageIndex==GridView.PageCount)
{
GridView1.PageIndex=1;
}
else
{ int pageno = GridView1.PageIndex+1;
GridView1.PageIndex=pageno;
}
GridView1.DataBind(); Timer1.Interval=600000;
}
PageIndex is zero-based index and PageCount is calculated by dividing the total number of records in the data source by the number of records displayed in a page (as specified by the PageSize property) and rounding up.
so PageIndex will never equal to PageCount
if(GridView1.PageIndex == (GridView1.PageCount -1))
{
GridView1.PageIndex = 0;
}
else
{
GridView1.PageIndex = GridView1.PageIndex + 1;
}
GridView1.DataBind();
You can use Ajax Update panel and put your grid inside the panel. Then you can use above code inside theOnTick event of Timer which set as AsyncPostBackTrigger, check below SO question for example
Timer in UpdatePanel
Edit:
Added onload method:
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;
}
I'm using a modal pop up extender to warn my customers that the item amount of a specific item is over a certain amount.
I have two buttons within this extender that allows a user to confirm they want an email sending to them when new stock arrives or not.
The trigger for the 'yes' button works perfectly but when i send the row ID to the constructor of my class used to store the email details it is always set to 0, even though the variable is global.
Here is my code to explain the issue further:
Button within my modal to add items to the cart:
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
TextBox t = (TextBox)row.FindControl("txtQuan");
*********Gain the item row ID (this is what needs to be passed*******
object ID = GridView1.DataKeys[row.RowIndex].Value;
*********This ID should be passed but is setting to 0************
rowID = Convert.ToInt32(ID);
string qty = t.Text;
int stockToAdd = Convert.ToInt32(qty);
DBHandler add = new DBHandler(rowID);
int qtyCheck = add.getStockQty();
if (stockToAdd > qtyCheck)
{
Button2_ModalPopupExtender.Show();
}
else{
SqlConnection con;
con = add.openDB();
con.Open();
DBHandler idCheck = new DBHandler(rowID);
int rows = idCheck.checkCartRows();
if (rows > 0)
{
int qtyNow = idCheck.getCartQty();
int updateStock = qtyNow + stockToAdd;
idCheck.updateQty(rowID, updateStock);
updatePanel();
}
else
{
idCheck.insertCart(qty);
updatePanel();
}
add.close();
}
}
The following code shows my confirm onclick button method. Note the ID 'rowID' that was stored in the above method when the add to cart button was clicked. This rowID is is setting to 0 instead of holding the rowID value.
protected void btnOK_Click(object sender, EventArgs e)
{
***** rowID is setting to 0*******
DBoutOfStockEmail insertNewEmailDetail = new DBoutOfStockEmail(IDMaster, rowID);
DBMembershipHandler getEmail = new DBMembershipHandler(IDMaster);
string emailToSend = getEmail.emailOfMember();
insertNewEmailDetail.insertDetails(emailToSend);
}
To summaries this question: Why is the rowID variable setting to '0' when i click the yes button with the modal pop up extender?
Based on my initial Comment I am going to post this as an answer
This can be from several things.. are you checking or doing IsPostBack checks, are you holding the Value(s) in a Session Variable..? ViewState is it enabled or disabled..? can you show what your Page_Load Event Looks like