I want to be able to update the table from c# with either a null or int. The dropdown will either have an id as the selected value or empty string, if it's an empty string I want to pass a null otherwise I want the id. I've tried this but getting an error "Input string was not in a correct format." Can anyone help? Thanks
var result = (from p in dc.Prices where p.price_ID == Id select p).FirstOrDefault();
result.no_update = String.IsNullOrEmpty((grd.Rows[e.RowIndex].FindControl("ddlNoUpdate") as DropDownList).SelectedValue.ToString()) ? System.Data.SqlTypes.SqlInt32.Null.Value : int.Parse((grd.Rows[e.RowIndex].FindControl("ddlNoUpdate") as DropDownList).SelectedValue.ToString());
dc.SubmitChanges();
Try using this code, it worked for me once
String insertedVal = (grd.Rows[e.RowIndex].FindControl("ddlNoUpdate") as DropDownList).SelectedValue.ToString()
result.no_update = String.IsNullOrWhiteSpace(insertedVal)
? (object)DBNull.Value : (object)insertedVal
Related
Please, I am trying to access my database to get access to a user id. But when i try accessing, what gets returned is 0. Initially, i had issues figuring out how to change this SQL statement (SELECT user_id FROM users WHERE firstname = 'Godymn') to LINQ. But i later found that i could use :
var result = users.Where(x=>x.firstname == "Godymn").Select(x=>x.userid);
So far, when i tried to use the query in my code, it returns a 0. But what i need is to return the user id based on the name specified in the linkLabel. I have not been able to figure out why its not working.
Will appreciate any help.
Here is my code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel())
{
result = db.users.Where(x => x.firstname == link).Select(x => x.user_id).FirstOrDefault();
}
return result;
}
Here is the button i used to check the content of what got returned.
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Good Afternoon Godymn.
Here are some possible scenarios:
1 - The user name Godymn does not exist in the database
2 - The user_id is 0.
Try checking this 2 scenarios.
After that, you could change your approach to a more "debug friendly" level.
var result = db.users.First(f => f.firstname == link);
Then, check if result is null. If it is null, the name was not found in the database.
If it is not null, check if the result is 0.
Why this approach: This way, you can tell if the problem is when you are searching for the user or when you are binding the value of Id.
I can't comment, i'm sory, but first of all i'll try this:
var foo = db.users.Select(x => x).ToList();
then you can investigate your result like this
i suppose you try get wrong data (or wrong structure)
when i stuck i do this:
Or maybe you can attach your structure of object?
So yeah, I was able to fix the bug. The problem was with the linkLabelPartner.Text as Chris Dunaway rightly said. As soon as he mentioned if the linklabel contains only firstname, I just knew that was the missing piece. This holds firstname and lastname and I only accounted for just firstname. Hence the value returned remains at 0. So, all I had to do was to concatenate both firstname and lastname which solved the issue. So, yeah the query I used initially was right.
Here is the code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel ())
{
result = db.users.Where(x => x.lastname + " " + x.firstname == link ).Select(x => x.users).FirstOrDefault();
}
return result;
}
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Many thanks everyone for your suggestions, appreciate.
I use his code for executing SQL query in entity framework :
using (var db = new VSServicesEntities())
{
const string selectCmd = #"if exists (Select top 1 IsUserOn From ServiceMembers Where ServiceCode={0} and Number={1})
Select isnull(IsUserOn,0) IsUserOn
From ServiceMembers Where ServiceCode={0} and Number={1}
else
Select Null IsUserOn";
var data = db.ServiceMembers.SqlQuery(selectCmd, "A", 091242535970).ToList();
if (data.Any())
{
var serviceMember = data.First().IsUserOn;
if (serviceMember.ToString() == "")
label1.Text = "";
else
label1.Text = (serviceMember.ToString() == "True" ? "On" : "Off");
}
}
but it gives me an exception :
Must declare the scalar variable "#ServiceCode".
but i give value to ServiceCode= A , what is the problem?
EDIT 2: I edited my query on top, but now it gives me another exception :
The data reader is incompatible with the specified 'VSServicesModel.ServiceMember'. A member of the type, 'ServiceCode', does not have a corresponding column in the data reader with the same name
but my column name is exactly : ServiceCode!! what is the problem??
You aren't passing parameters correctly:
var data = db.ServiceMembers.SqlQuery(selectCmd,
new SqlParameter("#ServiceCode", "A"),
new SqlParameter("#Number", 091242535970)).ToList();
Edit
The type that EF will attempt to assign to data is the type of the element of ServiceMembers (assuming ServiceMember). The only field you return is IsON which does not match the property IsUserOn which you reference. Try instead:
Select isnull(IsUserOn,0) AS IsUserON
...
Select Null AS IsUserON
Note that other properties will not be populated unless you return them from the query with matching names.
Edit You've changed your sql query - the binding was working correctly with ServiceCode=#ServiceCode and Number=#Number. At a guess, the reason why the Reader is complaining is because you are returning just one column (IsUserON) and trying to bind it to your full ServiceMember class. Either return all the columns (especially the primary key, presumably ServiceCode), or alternatively create a new class just with the property IsUserON and then use the generic type overload db.SqlQuery<MyNewPoco>(cmd, ...) to bind it.
I'm trying to update my table with this LINQ query
public void updateProduct(
int selectedIDToUpdate,
string prodNAMEToUp,
double prodPriceToUp,
string prodTYPEToUp,
int prodMANUToUp,
int prodCODEToUp)
{
DataClassesLINQEPOSDataContext dcld = new DataClassesLINQEPOSDataContext();
TBLPRODUCT tblprod = (from prod in dcld.TBLPRODUCTs
where prod.product_id == selectedIDToUpdate
select prod).First();
tblprod.product_name = prodNAMEToUp;
tblprod.product_price = prodPriceToUp;
tblprod.product_type = prodTYPEToUp;
tblprod.product_manufacturer = prodMANUToUp;
tblprod.product_code = prodCODEToUp;
dcld.SubmitChanges();
}
and then when I start to run the program I have this error
"InvalidCastException was unhandled"
"Specified cast is not valid."
Sorry I cant post image because I dont have enough reputation "points" :(
this is the control to pass the parameter on my class.
private void btnSaveToUpdate_Click(object sender, EventArgs e)
{
if (txtNameToUpdate.Text != "" ||
txtPriceToUpdate.Text != "" ||
txtTypeToUpdate.Text != "" ||
txtCodeToUpdate.Text != "")
{
Connection_Products update = new Connection_Products();
int selctedID = selectedIDToUpdate;
string prodNAMEToUp = txtNameToUpdate.Text;
double prodPriceToUp = double.Parse(txtPriceToUpdate.Text);
string prodTYPEToUp = txtTypeToUpdate.Text;
int prodMANUToUp = Convert.ToInt32(cmbManufacturerToUpdate.SelectedValue);
int prodCODEToUp = Convert.ToInt32(txtCodeToUpdate.Text);
update.updateProduct(selctedID, prodNAMEToUp, prodPriceToUp,
prodTYPEToUp, prodMANUToUp, prodCODEToUp);
}
else
{
MessageBox.Show("Error");
}
}
You most likely have some datatype mismatch between the values that you are trying to store and the data types of the columns in the database. This would be in one of the numeric columns.
If the prodPriceToUp column uses the money data type, this maps to a decimal type in Linq2Sql. You are trying to cast the double for the input parameter to decimal, which may be causing this issue. Try converting prodPriceToUp to a decimal before saving it.
I guess you are missing something in type mapping between updateProduct params and properties in tblprod. Please check here you are using correct types
This is because one of the following is trying to cast into an invalid type:
tblprod.product_name = prodNAMEToUp;
tblprod.product_price = prodPriceToUp;
tblprod.product_type = prodTYPEToUp;
tblprod.product_manufacturer = prodMANUToUp;
tblprod.product_code = prodCODEToUp;
Check for each of the these that the type of the left side is the same as the type of the right side. for example ensure that "tblprod.product_name" is a string property as you are trying to save a string to that property.
It is also possible that in your LINQ query, the where clause may have this problem, ensure that "prod.product_id" is an integer and not something else like a long or a short.
if these are all ok and you are still getting the exception then you will need to tell use what line is throwing the exception, and give use the details of the structure of tblprod;
On my ASP.NET MVC4 application, I need a dropdown-list to select a Location and insert its ID into a table, say News.
Some news apply to ALL Locations - therefore the LocationID in News is Nullable, to indicate this.
So I need to add "ALL Locations" to the dropdown.
This is how I imagined, it would work - but on the last line Value = DBNull.Value (or simple null) is not allowed. It only accepts an integer. I CANNOT use "0" as foreign key constraints on that table do not allow 0, because there is no ID=0 in Locations-table
var locations = db.Locations.Select(c => new { DisplayText = c.Location, Value = c.ID }).ToList();
locations.Insert(0, new { DisplayText = "All Locations", Value = DBNull.Value });
return Json(new { Result = "OK", Options = locations});
How can I add this to the options-list?
The basis of your locations anonymous object is created in the new {} operator in your Linq statement. If you need to allow for NULL, then... new { DisplayText = c.Location, Value = (int?)c.ID } explicitly set the anonymous type's Value parameter as nullable int. Then you can do Value = null on the next line when inserting.
I would like to query with linq some xml file. There are some required and some optional elements. Only required is name - everything else is optional.
If there is some NULL for example cageCode = NULL - it doesnt select anything - I need to add to List of strings - "" - I tried it like below, but it doesnt work. When I have everything filled it works fine, when there is something NULL it doesnt save to list anything.
Could you help me how to set "" to list where is null element?
Thanks!
var queryManufacturer = from dataManufaturer in input.Identification.Manufacturers.Manufacturer
select
new
{
dataManufaturer.name,
dataManufaturer.cageCode,
dataManufaturer.FaxNumber,
dataManufaturer.URL.OriginalString
};
foreach (var a in queryManufacturer)
{
data.Add(a.name);
if (a.cageCode == null) data.Add("");
else data.Add(a.cageCode);
if (a.FaxNumber == null) data.Add("");
else data.Add(a.FaxNumber);
if (a.OriginalString == null) data.Add("");
else data.Add(a.OriginalString);
}
It throws me a null exception if is some of elements in xml file missing - I dont wanna get this exception - I would like just add empty string beside missing element
try this in your Linq to XML query:
select new
{
name = dataManufaturer.name ?? "",
cageCode = dataManufaturer.cageCode ?? "",
FaxNumber = dataManufaturer.FaxNumber ?? "",
OriginalString = dataManufaturer.URL!=null ? dataManufaturer.URL.OriginalString : ""
};