Keep State of Gridview - c#

I have a gridview and I'm trying to keep the state of. Currently I have it where the user can edit inline( from within the gridview). Regularly I got this working:
protected void GridViewTower_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridViewTower.EditIndex = e.NewEditIndex;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
protected void GridViewTower_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridViewTower.EditIndex = -1;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
Problem is, I have 3 other features such sorting, dropdown that filters gridview, and a button search which also filters the girdview. When inline editing within any 3 of those modes, I can't control the state in which the gridview is in. Inside my gridview tag, I have both EnableViewState and ViewStateMode set to true.
How can I keep the state of the gridview within these modes?
public void LoadData()
{
if (Session["GridView"] != null)
{
GridViewTower.DataSource = Session["GridView"];
GridViewTower.DataBind();
//Response.Redirect("TowerManagement.aspx"); //
//Session["GridView"] = null;
}
else
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var tower = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
RangeName = t.Range.RangeName
}).ToList();
GridViewTower.DataSource = tower;
GridViewTower.DataBind();
ViewState["Sort"] = 0;
}
}
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = towers.CopyToDataTable();
gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
Session["GridView"] = GridViewTower.DataSource;
}

You don't need to store whole table in the Session or ViewState. Just store values of SortExpression, SortOrder etc. Here's an example how you can do it.
In my code I have added two private properties to store sortorder and sortexpression:
private string SortOrder
{
get
{
// Toggle order after sorting
string _order = "ASC";//Default
if( ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() =="DESC")
{
_order = "DESC";
ViewState["SortOrder"] = "ASC";
}
else
{
ViewState["SortOrder"] = "DESC";
}
return _order;
}
set
{
string _order = value.ToLower() == "descending"? "DESC" : "ASC";
ViewState["SortOrder"] = _order;
}
}
private string SortExpression
{
get
{
return ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "";
}
set
{
ViewState["SortExpression"] = value;
}
}
I have changed your GridView_Sort method to store the sort expression and sort order in newly added properties and called LoadData() method:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
//Disabled sort direction to enable toggling
//SortOrder = e.SortDirection.ToString();
LoadData();
}
The LoadData() method will be called from many places, whenever we want to load data into GridView. So I have changed it to this:
public void LoadData()
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = new DataTable();
gridviewTable.Columns.Add("TowerId");
gridviewTable.Columns.Add("TowerName");
gridviewTable.Columns.Add("rangeName");
foreach (var t in towers)
{
gridviewTable.Rows.Add(new object[] { t.TowerId, t.TowerName, t.rangeName });
}
if (!String.IsNullOrEmpty(SortExpression))
{
gridviewTable.DefaultView.Sort = String.Format("{0} {1}", SortExpression, SortOrder);
gridviewTable = gridviewTable.DefaultView.ToTable();
}
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
}
Initially I call the LoadData() method in Page_Load() :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
You can download the test project here.

Related

Gridview always show previous selected row

I am updating gridview after selecting row and then clicking edit which works perfectly but one thing is annoying me that whenever i visit that gridview that it shows that ROW SELECTED and Colored. Why ? i want fresh gridview with no record of previous selected data.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int ComplainantTypeID = Convert.ToInt32(txtSelectedID.Text.Trim());
ComplainantTypeBizz comBizz = new ComplainantTypeBizz(txtName.Text);
ManageComplainantType mngComplainantType = new ManageComplainantType();
bool Result = mngComplainantType.Update(comBizz, ComplainantTypeID);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtName);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
You have to bind the data to the gridview (GridView.DataBind();) after you edit it in the RowUpdated event and set the GridView.SelectedIndex = -1; after each data bind to unselect any row in your grid.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
Hope this helps.

How to override a session

I have a question can I overwrite a session that I allredy have set (I set the the user specific department)
Session:
int depId = user.HtDepartments.FirstOrDefault().DepartmentId;
Session["DepId"] = depId;
I want to override this id that I saved in the session with a new "id" that the user selectes out of the RadComboBox.
So when the user is coming back to this page not his "pre selected" department is selected , selected is the new department that he slected before
My code so far:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
this.parameterDepId = this.Request["depId"];
if (string.IsNullOrEmpty(parameterDepId))
{
parameterDepId = Session["depId"].ToString();
}
this.LoadDE(parameterDepId);
this.UserGrid.DataBind();
}
}
Loading the session
Here how I load my department
protected void LoadDE(string depId)
{
IEnumerable<HtDepartment> departments = null;
if (this.selectedBu != null)
{
departments = this.selectedBu.HtDepartments;
}
this.rcbDepartments.DataTextField = "Name";
this.rcbDepartments.DataValueField = "DepartmentId";
this.rcbDepartments.DataSource = departments;
this.rcbDepartments.DataBind();
this.rcbDepartments.Items.Insert(0, new RadComboBoxItem("-All-"));
if (depId != null)
{
int index = this.rcbDepartments.Items.IndexOf(this.rcbDepartments.Items.Where(i => i.Value == depId).SingleOrDefault());
if (index > -1)
{
this.rcbDepartments.Items[index].Selected = true;
this.selectedDepartment = departments.Where(i => i.DepartmentId == int.Parse(depId)).SingleOrDefault();
}
}
}
protected void rcbDepatments_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (this.rcbDepartments.Items.Count > 1 && this.rcbDepartments.SelectedIndex > 0)
{
this.selectedDepartment = HtDepartment.GetById(int.Parse(e.Value));
parameterDepId = this.selectedDepartment.ToString();
}
else
{
this.selectedDepartment = null;
}
this.dataSourceFilterChanged();
}
A resume of my question:
How and where should I override my session in the load method or in SelectedIndexChanged ?
It makes sense to check for the saved variable when loading a page, as the user won't be able to interact with the controls until this method has completed.
private void OnLoad(object sender, EventArgs e)
{
this.parameterDepId = this.Request["depId"];
}
But to override it with a new value you simply set a new value. Then the next time you loaded the page this newly set value would be returned in the OnLoad method.
private void MyControl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["DepId"] = MyControl.SelectedValue;
}
I'm finding your question a bit unclear but hopefully this answers the main point of it and helps with your code logic.

Dynamically created dropdowns and fired events accordingly

I have a simple task. first one Dropdownlist control is there where country name is loaded. After selecting country name, dynamically Dropdownlist will be loaded with corresponding state, after selecting state, dynamically another Dropdownlist will be added with relevant district. the problem is that the dynamically selected-index event is not fired. I searched it so many pages, but not find any suitable answer. can any one answer it for written code.
This code worked fine in static controls. but not dynamic controls.
Can any one correct my code
namespace fireProgram
{
public partial class MindforeSystemTestingProgram : System.Web.UI.Page
{
BALayer objBALayer = new BALayer();
DropDownList ddlState=new DropDownList();
DropDownList ddlDistrict=new DropDownList();
protected void Page_Init(EventArgs e)
{
ddlState.ID = "ddlState";
ddlState.AutoPostBack = true;
ddlState.SelectedIndexChanged += new EventHandler(ddlState_SelectedIndexChanged);
panel1.Controls.AddAt(2, ddlState);
ddlDistrict.ID = "ddlDistrict";
panel1.Controls.AddAt(3, ddlDistrict);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCountry.DataSource = objBALayer.GetCountry();
ddlCountry.DataTextField = "Text";
ddlCountry.DataValueField = "Value";
ddlCountry.DataBind();
}
//else
//{
// ddlState.ID = "ddlState";
// ddlState.AutoPostBack = true;
// ddlState.SelectedIndexChanged += new EventHandler(ddlState_SelectedIndexChanged);
// panel1.Controls.AddAt(2, ddlState);
// //ddlDistrict.ID = "ddlDistrict";
// //panel1.Controls.AddAt(3, ddlDistrict);
//}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int value = Convert.ToInt32(ddlCountry.SelectedValue);
panel1.Controls.AddAt(2, ddlState);
//DropDownList ddlState = new DropDownList();
//ddlState.AutoPostBack = true;
if (value != 0)
{
ddlState.DataSource = objBALayer.GetState(value);
ddlState.DataTextField = "Text";
ddlState.DataValueField = "Value";
ddlState.DataBind();
}
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
int value = Convert.ToInt32(ddlState.SelectedValue);
//DropDownList ddlDistrict = new DropDownList()
panel1.Controls.AddAt(3, ddlDistrict);
if (value != 0)
{
ddlDistrict.DataSource = objBALayer.GetDistrict(value);
ddlDistrict.DataTextField = "Text";
ddlDistrict.DataValueField = "Value";
ddlDistrict.DataBind();
}
}
}
}

How to store previous selected item from `DropDownList`

I have a DropDownList, using which I have to store some values from the CheckBoxList in the database.
Before I select another index from the DropDownList, the values in the CheckBoxList has to be stored, prompting the user with an alert "Save before proceeding".
I am able to display the above mention alert message. But the problem is once i change the index it DropDownList, the previous selected index is lost.
Can someone kindly help me getting the previous selected value and select the same dynamically in DropDownList. Because the value is need to store in database.
The code for displaying alert message is:
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
With the use of Global variables.
Using the code below. PreviousIndex will hold the previous, and CurrentIndex will hold current.
int PreviousIndex = -1;
int CurrentIndex = -1;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
PreviousIndex = CurrentIndex;
CurrentIndex = myDropdownList.Position; // Or whatever the get position is.
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
You can get the selected value first time the page load as
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Because When postback occurs the selected valued changed.
{
ViewState["PreviousValue"] = ddl.SelectedValue;
}
}
and in your selected index change event update your previous value by the new value as
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["NewValue"] = ddl.SelectedValue;
// Do your work with PreviousValue and then update it with NewValue so next you can acces your previousValue using ViewState["PreviousValue"]
ViewState["PreviousValue"] = ViewState["NewValue"];
}
or If you want to access selected value on different pages then save it in Session.
you can try with this code - bu using session caching
public string YourOldValue
{
get
{
if(Session["key"] != null)
return (string) Session["key"];
}
set
{
Session["key"] = value;
}
}
//Set value
YourOldValue = yourControl.SelectedValue;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SavedItem"] = LOC_LIST2.SelectedItem;
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
after you access on value or text
SelectedItem item = Session["SavedItem"] as SelectedItem;
if(item !=null)
{
string something= item.Value;
string otherthing =item.Text;
}
So here's what finally worked for me. A combination of the answers above.
You have to track both previous and current selected index/value in the OnLoad handler of the page/control.
private int PreviousSelectedIndex
{
get { return (Page.ViewSate["prevIdx"] == null) ? -1 : (int)ViewSate["prevIdx"]; }
set { Page.ViewSate["prevIdx"] = value; }
}
private int CurrentSelectedIndex
{
get { return (Page.ViewSate["currIdx"] == null) ? -1 : (int)ViewSate["currIdx"]; }
set { Page.ViewSate["currIdx"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
PreviousDropDownValue = ddlYourDropDownList.SelectedValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
else if (Page.IsPostBack && CurrentDropDownValue != ddlYourDropDownList.SelectedValue)
{
PreviousDropDownValue = CurrentDropDownValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
}
After that you can compare the previous and current values with each other.

cannot see the label content when a item is selected from dynamically added dropdownlist

I have a Dropdownlist (DDL1) when I select any item from this dropdownlist(DDL1), results in creation of another dropdownlist(DDL2), This contains some of the items.When I select other Item from DDL1 , Items will change in DDL2, this happens for the each different item selected in DDL1.
when I select a item from DDL2, label content must be shown, intially I'm making Label invisibe and in the code I changed the visibility to true and added content to it. But the label content is not shown when I select a item from DDL2.
Here is my Code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "Abe Books")
{
DropDownSeller.Visible = true;
lnkUsdBooks.Visible = true;
lnkUsdBooks.Text = "usedbooks#abe.com";
lnkUsdBooks.NavigateUrl = "mailto:usedbook#abe.com";
DropDownSeller.Visible = true;
DropDownSeller.Items.Remove("Chacha Choudary");
DropDownSeller.Items.Remove("SpiderMan");
DropDownSeller.Items.Remove("Amar chitra Katha");
DropDownSeller.Items.Remove("Chandamama");
DropDownSeller.Items.Remove("Mahabharata");
DropDownSeller.Items.Add("Amar chitra Katha");
DropDownSeller.Items.Add("Chandamama");
DropDownSeller.Items.Add("Mahabharata");
DropDownSeller.DataBind();
if (DropDownSeller.SelectedValue == "Amar chitra Katha")
{
lblPrice.Visible = true;
lblPrice.Text = "$69.99";
}
else if (DropDownSeller.SelectedValue == "Chandamama")
{
lblPrice.Visible = true;
lblPrice.Text = "$59.99";
}
else if (DropDownSeller.SelectedValue == "Mahabharata")
{
lblPrice.Visible = true;
lblPrice.Text = "$49.99";
}
else
{
lblPrice.Visible = false;
}
}
Any ideas on this are appreciated
Thanks,
Remove if (!Page.IsPostBack) from the DropDownList1_SelectedIndexChanged because when the page postbacks this condition will be false. Because your page is posting back to the server that's why it is not visible and not showing.
In short your DropDownList1_SelectedIndexChanged should be like..
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "Abe Books")
{
DropDownSeller.Visible = true;
lnkUsdBooks.Visible = true;
lnkUsdBooks.Text = "usedbooks#abe.com";
lnkUsdBooks.NavigateUrl = "mailto:usedbook#abe.com";
DropDownSeller.Visible = true;
DropDownSeller.Items.Clear(); // it will clear all the items, instead you are removing one by one
DropDownSeller.Items.Add("Amar chitra Katha");
DropDownSeller.Items.Add("Chandamama");
DropDownSeller.Items.Add("Mahabharata");
DropDownSeller.DataBind();
}
protected void DropDownSeller_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownSeller.SelectedValue == "Amar chitra Katha")
{
lblPrice.Visible = true;
lblPrice.Text = "$69.99";
}
else if (DropDownSeller.SelectedValue == "Chandamama")
{
lblPrice.Visible = true;
lblPrice.Text = "$59.99";
}
else if (DropDownSeller.SelectedValue == "Mahabharata")
{
lblPrice.Visible = true;
lblPrice.Text = "$49.99";
}
else
{
lblPrice.Visible = false;
}
}

Categories

Resources