Why is this sporadically throwing a null reference error? - c#

Okay, this code sporadically throws a null reference error because the return ((AVMain)this.Page).Model isn't returning anything. I have not been able to make this error recur, even with the same ID value that fails for other people. Any help would be greatly appreciated!
protected AVModel Model
{
get
{
return ((AVMain)this.Page).Model;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (SessionData.IsAudit.HasValue && SessionData.IsAudit.Value == true)
{
cbFlagAudit.Visible = false;
}
if (!IsPostBack)
{
cbFlagAudit.Checked = this.Model.FlagForAudit.HasValue ? this.Model.FlagForAudit.Value : false;
}
}

I'd start by adding some null-reference checks throughout the logic. That should prevent a NullReferenceException from being thrown.
How's this?
protected AVModel Model
{
get
{
if(this.Page is AVMain)
{
var page = this.Page as AVMain;
return page.Model;
}
return null;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (SessionData.IsAudit.HasValue && SessionData.IsAudit.Value == true)
{
cbFlagAudit.Visible = false;
}
if (!IsPostBack)
{
var model = this.Model;
Boolean? value = null;
if(model != null)
{
value = model.FlagForAudit;
}
cbFlagAudit.Checked = (value.HasValue && value.Value)
}
}

Thank you all for your advice, but the error was actually being generated due to a permissions error in the database. It was causing a stored procedure to fail and not return the data needed to populate the object, hence it was null. The initial developers did not put error trapping in this project, so something that should taken no time to find, took a few days. ALWAYS trap your errors!

Related

The type 'System.Void' may not be used as a type argument! Error occurs

I am getting weird error on c# winforms. I summarize the problem step by step.
I have 1 model (public class)
I have a winform that includes a datagridtable and this is binded to model.
Winfom.cs is opened.
Close the visual studio and reopen.
I am getting error as below :
at System.RuntimeType.
ThrowIfTypeNeverValidGenericArgument(RuntimeType type)
SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParamters)
MakeGenericType(Type[] instantiation)
at System.Windows.Forms.BindingSource.
CreateBindingList(Type type)
GetListFromType(Type type)
ResetList()
System.ComponentModel.ISupportInitialize.EndInit()
When I click the error message it forwards me the winform.designer.cs below
(System.ComponentModel.ISupportInitialize)(this.tankModelBindingSource).EndInit();
I close all of them without any change & reopen the winform.cs (designer)
Error is gone!
Am I missing something? Every time do I have to get this error? Is this a bug or not?
Thanks.
public void datagridFixedItemVisualization()
{
fixedItemModelBindingSource.DataSource = MainParticularsModel.FixedItemList;
}
private void dgTankSet_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// CALCULATING....
dgTankSet.DataSource = MainParticularsModel.TankList;
dgTankSet.Refresh();
}
private void cmbCatFilter_SelectedIndexChanged(object sender, EventArgs e)
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dgTankSet.DataSource];
currencyManager1.SuspendBinding();
TankCategory cmbfiltername = (TankCategory)Enum.Parse(typeof(TankCategory), cmbCatFilter.SelectedItem.ToString());
switch (cmbfiltername)
{
case TankCategory.ALL:
makeALLrowsVisible();
currencyManager1.ResumeBinding();
break;
case TankCategory.ETC:
makeALLrowsVisible();
foreach (DataGridViewRow row in dgTankSet.Rows)
{
if (row.Cells[0].Value.ToString() != "ETC")
{
row.Visible = false;
}
}
currencyManager1.ResumeBinding();
break;
}
}
private void btnAddFixedItem_Click(object sender, EventArgs e)
{
using (FixedItemForm frm = new FixedItemForm() {FixedItemInfo=new FixedItemModel() })
{
if (frm.ShowDialog() == DialogResult.OK)
{
MainParticularsModel.FixedItemList.Add(frm.FixedItemInfo);
fixedItemModelBindingSource.ResetBindings(false);
fixedItemModelBindingSource.DataSource = MainParticularsModel.FixedItemList;
dgFixedItems.Update();
dgFixedItems.DataSource = fixedItemModelBindingSource;
}
}
}

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.

Reloading and Updating using Entity Framework and DBContext

Ok so I have tried a few things and keep getting stuck. I had the update button working at one point and now it will not update. The delete button will work and delete records but I can not get the gridview to refresh after the record is deleted. I also want the gridview to reload after the update button is pressed and the record is updated. Here is what I have:
protected void btnDelete_Click(object sender, EventArgs e)
{
switch (btnDelete.Text)
{
case DeleteButton:
try
{
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location locationCheck = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
if (locationCheck != null)
{
Location n = new Location
{
Id = grdvwLocationList.SelectedIndex,
Name = txtLocationName.Text,
SubAccount = txtSubAccountName.Text
};
_context.Locations.Remove(n);
_context.SaveChanges();
}
}
}
catch (Exception)
{
lblLocationNameNotification.Text = "Please type in a location/sub-account or select a location/sub-account that doesn't have a asset to delete.";
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
break;
case CancelButton:
Reload();
break;
}
}
public void PopulateLocationGridView()
{
var locations = _context.Locations.Where(l => l.CompanyId == CompanyId)
.OrderBy(l => l.Name)
.ToList();
grdvwLocationList.DataSource = locations;
grdvwLocationList.DataBind();
if (locations.Count > 0)
{
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
else
{
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
}
The add button works just fine it just seems to be refreshing the grid view
I have the following exampe working in a winforms application
The trick is the dset.local
private void Form1_Load(object sender, EventArgs e)
{
var dset = Db.Tasks; // Db is my context.
DbSet<Task> qry = dset;
qry.Load();
bindingSource1.DataSource =dset.Local.ToBindingList();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Debug.Print(Db.Tasks.Count().ToString());
bindingSource1.EndEdit();
Db.SaveChanges();
}
After working on it last night I knew there was something that I was missing. I ended up going about it like this:
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
_context = new IMSDBContext();
switch (btnDelete.Text)
{
case DeleteButton:
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location location = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
_context.Locations.Remove(location);
_context.SaveChanges();
PopulateLocationGridView();
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
break;
case CancelButton:
Reload();
break;
}
}
catch (Exception ex)
{
lblLocationNameNotification.Text = ex.Message;
}
finally
{
if (_context != null)
{
_context.Dispose();
}
}
}
I had tried to use the PopulateLocationGridView() and RowSelect() methods by themselves and it was still having trouble. I ended up putting in the grdvwLocationList.SelectedIndex = 0; in to set the selected index on the first index in the list instead of the index of the record that I just deleted. That is where I was having trouble. I thought that the SelectRow() would reselect the index again but I had to reset it back to another index. If there are any questions or comments please feel free. I am still learning and would like all of the advise that I can get.

Linq update query

I want to update an existing record. I also have debugged my code. The int id variable gets the value, but I don't know why my record doesn't updated.
SQLDBDataClassesDataContext dContext = new SQLDBDataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["fname"]))
{
FirstNameTextBox.Text = Request.QueryString["fname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["lname"]))
{
LastNameTextBox.Text = Request.QueryString["lname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["cellnum"]))
{
CellNumberTextBox.Text = Request.QueryString["cellnum"];
}
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
var updatequery1 = dContext.PersonalDetailTables
.Where(pd => pd.ID == id).SingleOrDefault();
if (updatequery1 != null)
{
updatequery1.FirstName = FirstNameTextBox.Text;
updatequery1.LastName = LastNameTextBox.Text;
updatequery1.CellNumber = CellNumberTextBox.Text;
dContext.SubmitChanges();
}
}
if (updatequery1 != null)
is updatequery1 null? If it's now, it'll just skip right over. Setup a breakpoint and step through.
Alternatively, change .SingleOrDefautl to .Single instead. This way if nothing's found, u'll get an exception, and u'll know what's up.
Call dContext.InsertOnSubmit(fooentity) method before calling dContext.SubmitChanges();.
For example.
var ctx = DB.fooDB;
fooobj.fooName= bar.fooName;
fooobj.fooID= bar.fooID;
if (fooobj.fooID== 0)
ctx.Locations.InsertOnSubmit(bar);
ctx.SubmitChanges();
I`ve got my Solution..
the only problem was of if(!ispostback) issue.
context.InvProductStockMasters
.Update(ps => ps.LocationID.Equals(invStockAdjustmentHeader.LocationID)
&& ps.ProductID.Equals(invStockAdjustmentDetail.ProductID),
ps => new InvProductStockMaster
{ Stock = ps.Stock - invStockAdjustmentDetail.OrderQty });

ASP.NET LINQ (C#) UPDATE SYNTAX

I am using LINQ to Entities in an ASP.NET C# app. The below code is my attempt to update (or reset, really) a value 'AvgRideTime' in my sql db to null. However it seems to do nothing, no errors, just nothing. Any thoughts?
protected void ResetAvgRT_Click(object sender, EventArgs e)
{
using (RamRideOpsEntities myEntities = new RamRideOpsEntities())
{
var avgTime = (from a in myEntities.AdminOptions
select a.AvgRideTime).First();
if (avgTime != null)
{
avgTime = null;
myEntities.SaveChanges();
}
}
}
var avgTime = myEntities.AdminOptions.First();
if (avgTime != null)
{
avgTime.AvgRideTime = null;
myEntities.SaveChanges();
}
Try the above code.
avgTime this is link to object and when you set avgTime = null, avgTime no referenced to object, but myEntities.AdminOptions contains this object.
Maybe the avgTime gets a null value.
Try the following code
protected void ResetAvgRT_Click(object sender, EventArgs e)
{
using (RamRideOpsEntities myEntities = new RamRideOpsEntities())
{
var avgTime = (from a in myEntities.AdminOptions
select a).First();
if (a.avgTime != null)
{
a.avgTime = null;
myEntities.Entry(a).State = EntityState.Modified;
myEntities.SaveChanges();
}
}
}

Categories

Resources