I have an issue where I add data to my database from my WCF application, but I get the following error when stepping over the code snippet below:
Nullable object must have a value.
foreach (var sectionGroup in quote.Items.First().SectionGroups)
bills.Add(new ListOfBills
{
Cost = (double)sectionGroup.Cost,
PricePerMeter = sectionGroup.Price_m,
GroupName = sectionGroup.SectionGroup.Name,
Length = sectionGroup.Length,
Quantity = (double)sectionGroup.Quantity,
StockCode = sectionGroup.StockItem.StockCode,
StockDescription = sectionGroup.StockItem.Description,
TruckSection = sectionGroup.SectionGroup.Section,
Weight = (double)sectionGroup.Weight,
Width = sectionGroup.Width
});
return bills;
The thing is that from my WPF application where I access the data and display the information in a datagrid, some of the rows will have be null depending the user's selection from the comboboxes.
So my question is that, is there a way to not display the null rows of data or just add them to the database with the value as null and how can I get past the nullable error from above?
Thanks in advance! :)
You can try to use DBNull.Value to represent NULL in DB, so it should solve your error.
In every place you want to add a null add DBNull instead, here's an example:
Cost = sectionGroup.Cost == null ? DBNull.Value : (double)sectionGroup.Cost
Related
Is this a correct understanding of what this code does - and is it the correct way to update a row which has a URLPath of url so that the IsInProcessing column is true?
I haven't actually tried this code yet. Before I do, I want to try and understand it! It is pieced together from various sources.
The code:
using(var db = new DamoclesEntities())
{
var urls = db.URLS;
var result = urls.FirstOrDefault(u => u.URLPath == url);
result.IsInProcessingQueue = true;
db.SaveChanges();
}
What I think is happening here is within the using I am instantiating the DamoclesEntities() class as var db.
I then instantiate the db.URLS (class / table) to the var urls.
I then find the first row where the URLPath (column) contains url, and that row is assigned to result.
I change that row's IsInProcessingQueue (column value) to true;
Finally, I save the changes to the database.
it is almost correct, but keep in mind, that FirstOrDefault will return null value in case if there is no rows found by specified criteria - URLPath == url.
So in this case next row will produce NullReferenceException.
Just add check of result for a null and do result.IsInProcessingQueue = true;db.SaveChanges(); only if result != null
I have got a problem. While updating a row in the table by Linq To Sql,
I want to know the only changed fields.
Suppose I have 25 fields in a page but I only updates 3 fields and at the time of updation, I need to get only those 3 fields, it's old value + it's modified or new value.
Can IT be possible in the Linq To Sql.
I was searching the things on internet and have come to know about DB.GetChangeSet() but it just gives me the modified row.
I have checked other questions related to same from here but I did'nt get the way they were using I also tried but it is giving me error "Sequence contains no elements"
I tried in this way::
where TableClass ObjTbl in the function parameter is the Object containing the new values from the model.
public int UpdateDetails(int Id, TableClass ObjTbl)
{
using (DataContext DB = new DataContext())
{
var Data = DB.TableClass.Where(m => m.PkId == Id).FirstOrDefault();
Data .FirstName = ObjTbl.FirstName;
Data .MiddleInitials = ObjTbl.MiddleInitials;
Data .FkClientID = ObjTbl.FkClientID;
Data .LastName = ObjTbl.LastName;
DB.SubmitChanges();
TableClass instance = DB.GetChangeSet().Updates.OfType<TableClass>().Where(m => m.PkId == Id).First();
DB.TableClass.GetModifiedMembers(instance);
}
}
You need to check for your changes before you call SubmitChanges.
Also, in your example the line
TableClass instance = DB.GetChangeSet().Updates.OfType<TableClass>().Where(m => m.PkId == Id).First();
will throw an exception if nothing was changed, otherwise it will return the record you are amending ie, Data, so you may as well just do something like
ModifiedMemberInfo[] changes = DB.TableClass.GetModifiedMembers(Data);
If nothing has been changed, then this will return an empty array, rather than throw an exception.
I'm having problems deleting from my database
I have the following
Member thisMember = db.Members.First(m => m.MemberID == member.MemberID);
db.Members.Remove(thisMember.Name);
db.Members.Remove(thisMember.LastName);
But I keep getting an invalid arguments error. Can someone assist me?
Thanks!
db.Members.Remove is used to remove whole record (row/object) from data source. So you can remove whole member like this:
db.Member.Remove(thisMember);
If you want to set values of thisMember then you can do it like this:
Member thisMember = db.Members.First(m => m.MemberID == member.MemberID);
thisMember.Name = "";
// provided that it allows null value
thisMember.LastName = null;
// save changes in data source
db.SaveChanges();
I have a form where I have 4 dropdowns Country, State, District and City. Country is populated on form load and rest are populated on selected index changed event. The sequence is On Country's selected index changed States are populated. On State-> Districts populated and on Districts -> Cities are populated.
For saving it worked fine but when i was updating value, it shows null reference error. On debugging I got, the dropdowns are not populated, whereas I was trying set values. Below is my code.
using (var manager = new LocationManager())
{
var dt = manager.GetLocationById(i);
if (dt.Rows.Count == 1)
{
Countries.SelectedValue = Countries.Items.FindByText(dt.Rows[0]["Country"].ToString()).Value;
BindStates(Convert.ToInt32(Countries.SelectedItem.Value));
States.SelectedValue = States.Items.FindByText(dt.Rows[0]["State"].ToString()).Value;
BindDistricts(Convert.ToInt32(States.SelectedItem.Value));
Districts.SelectedValue = Districts.Items.FindByText(dt.Rows[0]["District"].ToString()).Value;
BindCities(Convert.ToInt32(Districts.SelectedItem.Value));
Cities.SelectedValue = Cities.Items.FindByText(dt.Rows[0]["City"].ToString()).Value;
Pincode.Text = dt.Rows[0]["Pincode"].ToString();
ViewState["Id"] = dt.Rows[0]["LocationId"].ToString();
}
}
I am getting error: {"Object reference not set to an instance of an object."} at method
BindStates(Convert.ToInt32(Countries.SelectedItem.Value));
I think the problem is not with the population of drop downs, but with finding values, when
Countries.Items.FindByText(dt.Rows[0]["Country"].ToString())
wont find any matching value it will return null. So applying 'Value' property on null is giving the error.
you can put a null check before selecting it.
something like below:
countryDropDown.SelectedValue = countryDropDown.Items.FindByText(dt.Rows[0]["Country"].ToString()) != null ? countryDropDown.Items.FindByText(dt.Rows[0]["Country"].ToString()).Value : countryDropDown.Items.FindByText("-Please select-").Value;
Check if Countries.SelectedItem != null
#Amit Ranjan: Bind all values in page init method and at page load make the perticular value selected for all drop downs:
you are getting null reference because, there is no value already bind to the drop down.
At page init bind all values to dropdown
India
US
UK
asp:DropDownList>
At page load
DropDownList .SelectedValue= dt.Rows[0]["Country"].ToString()).Value;
I have a datatable with data in it (customer addresses). In some instances, column ADDR3 doesn't have a value and column ADDR2 does. I'm attempting to check the value of ADDR3 and if it doesn't contain a value I want to copy the value in ADDR2 to ADDR3 and then blank out ADDR2. I was trying to use the below code, but it isn't working. I placed a breakpoint after my 'if' statement, but the program never breaks. But, I know for a fact that a lot of the rows have null ADDR3 fields. Can anyone tell me what I'm doing wrong?
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
object value = row["ADDR3"];
if (value == DBNull.Value)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}
It's likely that your row["ADDR3"] value is NEVER equal to DbNull.Value. This is often the case with data tables that were transferred over a web service, for example (there will be empty strings instead of nulls due to the XML transformations).
Put a break point BEFORE your if and find exactly what the value is. You might try checking for row["ADDR3"] == null or string.IsNullOrWhiteSpace(row["ADDR3"].ToString())
Have you tried comparing the value to null (rather than DBNull.Value)? I believe DBNull.Value is exclusive for certain database objects and does not appear once read into a dataset/datatable.
Try this:
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
if (
row.IsNull("ADDR3") // True if the value is null
||
String.IsNullOrWhitespace(row["ADDR3"]) // True if the value is "", " ", etc.
)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}