Maintaining session object in webforms - c#

What I am attempting to do is preserve a session object that stores a Dictionary .
I need this dictionary in order to keep a running list that matches up to an asp:Gridview.
Every time the page loads, I'm checking the Dictionary and highlighting any matches in the Gridview.
However, every time Page_Load occurs, the Session["Rolls"] is coming up as null. Now, I'm also highlighting matching entries in a buttonClick event and the Dictionary is preserved up until I initiate a different event (like another button click OR GridView_RowEditing/GridView_RowUpdating). Are there any principals of Session variables that I'm not paying attention to?
Google Chrome console also recognizes the Session throughout every action, but in Debug, every Page_Load brings up a null Session["Rolls"].
Here's my Page_Load code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["Rolls"] = new Dictionary<string, int>();
}
else
{
WoSource.SelectCommand =
"SELECT WorkOrderNo, RollNumber, ModelNumber, QtyGood, QtyRun FROM RFID_Inventory WHERE WorkOrderNo= '" + woText.Text + "'";
var currentDict = (Dictionary<string, int>) Session["Rolls"];
if (currentDict == null)
{
}
else
{
foreach (var entry in currentDict)
{
foreach (GridViewRow row in GridView1.Rows)
{
var dataKey = GridView1.DataKeys[row.RowIndex];
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 0))
{
row.BackColor = System.Drawing.Color.Red;
break;
}
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 1))
{
row.BackColor = System.Drawing.Color.Green;
break;
}
}
}
}
}
}
EDIT: Discovered that the RowEditing/RowUpdating events are not preserving the GridView Backcolor highlighting that I'm doing.
Is there something I can add to those event calls?
Here is my RowEditing event:
protected void GridView1_RowEditing(object sender, EventArgs e)
{
var currentDict = (Dictionary<string, int>)Session["Rolls"];
if (currentDict == null)
{
}
else
{
foreach (var entry in currentDict)
{
foreach (GridViewRow row in GridView1.Rows)
{
var dataKey = GridView1.DataKeys[row.RowIndex];
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 0))
{
row.BackColor = System.Drawing.Color.Red;
break;
}
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 1))
{
row.BackColor = System.Drawing.Color.Green;
break;
}
}
}
}
}
EDIT2: My issue was solved. My session wasn't coming back null. I actually needed to add my GridView highlighting method to the GridView_RowDataBound event. Turns out I was just trying to highlight the gridview at the wrong time. I marked the Kishore's answer as correct so that users can see my reply. Thanks for everybody's help.

As i look your code you are initialize session variable on page load so you lost the state. you can put a null check before initialize session variable.

Well What we do for managing our Global Object into session is Encapsulating them in Property. Lets have a look in this:
public Dictionary<string, int> Rolls
{
get
{
if(Session["Rolls"] == null)
return new Dictionary<string, int>();
else
return (Dictionary<string, int>)Session["Rolls"];
}
set
{
Session["Rolls"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Now Accessing Rolls in page will be directly hitting Session.
// and Get property will give New dictionary object with 0 record instead of null
// Otherwise it will return Object already caste into dictionary object
foreach (var entry in Rolls)
{
}
// We always can assign new Dictionary object in Session by
Rolls = new Dictionary<string, int>(10); // for example dictionary with 10 items
}
So we can use our Get Set in Parent class of Web page to make it accessible on all child classes. We can use similar approaches for View state and Cache objects as well.
Let me know if you have any question.

Related

How can I get the value of the data contained in the Asp Dropdown?

There are 4 values in my dropdown list, and if there is an "x" value in it, I want to hide that value. How can I do this using the If command.
protected void dr_alans_DataBound(object sender, EventArgs e)
{
if (dd_mainAlan.SelectedItem.Text == "Yönetici")
{
if (dr_alans.Items.FindByValue("22").Value=="22")
{
dr_alans.Items.FindByValue("22").Enabled = false;
}
else if (dr_alans.Items.FindByValue("23").Value == "23")
{
dr_alans.Items.FindByValue("23").Enabled = false;
}
}
}
If it is ASP.NET Forms, you should be able to do it like this maybe. This should hide the items with an x in the Value.
foreach (var itm in dd_mainAlan.Items)
{
var it = (ListItem)itm;
it.Enabled = !it.Value.Contains("x");
}

listbox and search returning null

I have a search function which works good the first time i run it. When i try adding a new search the program shuts down giving me the error message:
"markerat = listBoxSökResultat.SelectedItem.ToString().ToLower(); Object reference not set to an instance of an object. NullReference.
Ive tried using if and return; but that doesnt seem to help. Anyone knows whats wrong here?
private void buttonSökNamn_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
var v = (from x in el.Descendants("recept")
where x.Element("namn").Value.ToLower().Contains(textBoxNamn.Text.ToLower())
select x);
if (v == null)
{
MessageBox.Show("Finns inte!");
return;
}
foreach (var item in v.Elements("namn"))
{
Sökresultat.Add(item.Value);
}
listBoxSökResultat.DataSource = null;
listBoxSökResultat.DataSource = Sökresultat;
}
private void listBoxSökResultat_SelectedIndexChanged(object sender, EventArgs e)
{
string markerat;
markerat = listBoxSökResultat.SelectedItem.ToString().ToLower();
if (markerat == null) return;
listBox1.Items.Clear();
if (listBoxSökResultat.SelectedItems.Count == 0) return;
var v = (from x in el.Descendants("recept")
where x.Element("namn").Value.ToLower() == markerat
select x).FirstOrDefault();
if (v == null)
{
MessageBox.Show("Finns inte!");
return;
}
textBoxNamn.Text = v.Element("namn").Value;
listBox1.Items.Add(v.Element("portioner").Value);
var test = v.DescendantsAndSelf("ingrediens").ToList();
foreach (var item in test)
{
listBox1.Items.Add(item.Value);
}
var test2 = v.DescendantsAndSelf("steg").ToList();
foreach (var item in test2)
{
listBox1.Items.Add(item.Value);
}
}
listBoxSökResultat.SelectedItem is what is null, so any further calls (.ToString()) will cause that exception. You are currently checking it's not null and SelectedItems has a count higher than 0, but after the problem occurs. By then it's too late. That defensive checking is great, but you are doing it a little too late.
SelectedItem will be null if there is no selected item at the time, so you should check that first:
if (listBoxSökResultat.SelectedItem != null)
{
markerat = listBoxSökResultat.SelectedItem.ToString().ToLower();
}
That will let you pass this particular problem.

If all rows data is null hide column

Using MS Visual Studio 2012, Telerik, C#.ASP.NET.
The logic I need is as follows:
If a columns data on all rows is null then hide the column
Basically if a column has 3 rows of data, if there all null then dont bother displaying that column, however if there is a value in 1 of them, then show the column.
been playing around:
foreach (GridColumn columns in dgvUserResults.Columns)
{
if (columns != null)
{
columns.Visible = false;
}
else
{
columns.Visible = true;
}
}
code doesn't work of course doesnt iterate through the foreach loop just skips it. Although not bothered about that even if it did iterate through I need a way to check if all column[name] rows are null. There a nice Telerik one liner?
Please try with below code snippet.
Using UniqueName
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
{
// If you used ClientSelectColumn then below code is not worked For that you have to put condition
//if(column.ColumnType == "GridBoundColumn")
int TotalNullRecords = (from item in RadGrid1.MasterTableView.Items.Cast<GridDataItem>()
where string.IsNullOrWhiteSpace(item[column.UniqueName].Text) ||
item[column.UniqueName].Text == " "
select item).ToList().Count;
if (TotalNullRecords == RadGrid1.MasterTableView.Items.Count)
{
RadGrid1.MasterTableView.Columns.FindByUniqueName(column.UniqueName).Visible = false;
}
}
}
By Using Index
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
{
// If you used ClientSelectColumn then below code is not worked For that you have to put condition
//if(column.ColumnType == "GridBoundColumn")
int TotalNullRecords = (from item in RadGrid1.MasterTableView.Items.Cast<GridDataItem>()
where string.IsNullOrWhiteSpace(item[column.UniqueName].Text) ||
item[column.UniqueName].Text == " "
select item).ToList().Count;
if (TotalNullRecords == RadGrid1.MasterTableView.Items.Count)
{
column.Visible = false;
}
}
}
For col = 0 To myRadGridView.ColumnCount
Dim mustKeepColumn As Boolean = False
For Each r In myRadGridView.Rows
If Not String.IsNullOrEmpty(r.Cells(col).Value.ToString) Then
mustKeepColumn = True
Exit For
End If
Next
If Not mustKeepColumn Then
myRadGridView.Columns(col).IsVisible = False
End If
Next

Checkbox group not detecting if checked

So I am recieving some postback data back from a form and need to get the checkbox values for a group of checkboxes in a parent control. I coded it up and it was working but now no longer works and I can not figure out why. The checkboxes are created on page load dynamically but on postback nothing seems to be checked when the form had checked items, the only postback event is the submit button event.
// This is from the btnSubmit Postback event that isn't working anymore
foreach (CheckBox cb in ShowPermissions.Controls.OfType<CheckBox>())
{
if (cb.Checked)
{
// Add New Admins Permissions
Permission p = new Permission();
p.AdminUserID = au.id;
p.AdminMenuID = Convert.ToInt32(cb.ID.ToString().Substring(4));
ngdb.Permissions.InsertOnSubmit(p);
submitResult.InnerHtml += cb.ID.ToString();
// Does not run now?
}
// can see the checkbox object
}
protected void Page_Load(object sender, EventArgs e)
{
FunctionType = Request.QueryString["func"] != null && Request.QueryString["func"] != "" ? Request.QueryString["func"] : null;
RID = Request.QueryString["rid"] != null && Request.QueryString["rid"] != "" ? int.Parse(Request.QueryString["rid"]) : -1;
PopulateAdminTypes();
if (!IsPostBack && FunctionType == "edit" && RID != -1)
{
// Populate User details for Edit
PopulateUser(RID);
// Populate checkboxes and check selected options
PopulateAdminPermissionOptions(true, RID);
// Disable password change
ChangePassword(false);
}
else if (!IsPostBack)
{
chkChangePassword.Visible = false;
PopulateAdminPermissionOptions(false, -1);
}
}
private void PopulateAdminPermissionOptions(bool blnPopulateForEdit, int RID)
{
// Get Logged in Admin ID
int intAdminId = Convert.ToInt32(Session["AdminID"]);
int intAdminTypeId = Convert.ToInt32(Session["AdminTypeID"]);
using (NewGeorgeDataContext ngdb = new NewGeorgeDataContext())
{
var am = ngdb.AdminMenus.AsQueryable();
// Hide Add and Edit Options from Non Super Users
var amUsers = ngdb.AdminMenus.Where(x => x.id > 2 && x.id < 5);
if (intAdminTypeId > 1) am = am.Except(amUsers);
foreach (var m in am.OrderBy(x => x.MenuTypeID).ThenBy(x => x.id))
{
// Add New CheckBox
CheckBox cb = new CheckBox();
cb.ID = "chk_" + m.id;
cb.CssClass = "chkItems";
cb.Text = m.AdminMenuType.Name + ": " + m.Name;
// Get Admin Permission objects
if (blnPopulateForEdit)
{
var ap = ngdb.Permissions.SingleOrDefault(x => x.AdminUserID == RID && x.AdminMenuID == m.id);
if (ap != null)
{
cb.Checked = true;
}
}
ShowPermissions.Controls.Add(new LiteralControl("<p>"));
ShowPermissions.Controls.Add(cb);
ShowPermissions.Controls.Add(new LiteralControl("</p>"));
}
}
}
Can someone workout what I cannot see atm?
The view state isn't getting load into your controls. You must create all the controls before LoadViewState triggers. So, create all dynamic Controls OnPageInit event or Page_Init method to get the correct behavior. Take a look here to get more information about Asp.NET Page Life Cycle
Hopes this help you!

Retain the user defined sort order in WPF DataGrid

I have a WPF DataGrid that is populated with data from DataSet. I have CanUserSortColumns set to true.
Is it possible to retain the sorting that the user specified when the grid is refreshed? I have it retaining the item that was selected using
object selectedItem = dgInvoiceHeads.SelectedItem;
before the refresh takes place and then placing
dgInvoiceHeads.SelectedItem = selectedItem;
after the refresh takes place.
But I can't seem to get it to retain the specified sort.
The following code was pulled from this forum post and it shows how to obtain the sort descriptions and column information and restore it.
List<DataGridColumn> GetColumnInfo(DataGrid dg) {
List<DataGridColumn> columnInfos = new List<DataGridColumn>();
foreach (var column in dg.Columns) {
columnInfos.Add(column);
}
return columnInfos;
}
List<SortDescription> GetSortInfo(DataGrid dg) {
List<SortDescription> sortInfos = new List<SortDescription>();
foreach (var sortDescription in dg.Items.SortDescriptions) {
sortInfos.Add(sortDescription);
}
return sortInfos;
}
void SetColumnInfo(DataGrid dg, List<DataGridColumn> columnInfos) {
columnInfos.Sort((c1, c2) => { return c1.DisplayIndex - c2.DisplayIndex; });
foreach (var columnInfo in columnInfos) {
var column = dg.Columns.FirstOrDefault(col => col.Header == columnInfo.Header);
if (column != null) {
column.SortDirection = columnInfo.SortDirection;
column.DisplayIndex = columnInfo.DisplayIndex;
column.Visibility = columnInfo.Visibility;
}
}
}
void SetSortInfo(DataGrid dg, List<SortDescription> sortInfos) {
dg.Items.SortDescriptions.Clear();
foreach (var sortInfo in sortInfos) {
dg.Items.SortDescriptions.Add(sortInfo);
}
}
Have you tried getting the collectionview for the dataset?
CollectionViewSource.GetDefaultView(yourDataSet).SortDescriptions
This will give you an array of the current sortdescriptions. You can then persist these, and the next time round apply them as follows
CollectionViewSource.GetDefaultView(yourDataSet).SortDescriptions.Add(...)
Hope it helps.
One of my colleagues came up with this. It seems to be working correctly. The only thing is I think the column headers need to be the same in the DataGrid as they are in the DB.
string sortHeader;
string prevSortHeader;
SortDescription sd;
private void dgInvoiceHeads_Sorting(object sender, DataGridSortingEventArgs e) {
sortHeader = e.Column.Header.ToString();
if (sortHeader == prevSortHeader) {
sd = new SortDescription(sortHeader, ListSortDirection.Descending);
}
else {
sd = new SortDescription(sortHeader, ListSortDirection.Ascending);
}
prevSortHeader = sortHeader;
}
HTH
private void testGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ?
ListSortDirection.Ascending : ListSortDirection.Descending;
// You will get the current direction in direction
}
This is another solution

Categories