How do I modify the query below to properly handle the case where the "Summary" element is missing from one of the articles? Now when that happens I get an "Object reference not set to an instance of an object."
var articles = from article in xmlDoc.Descendants("Article")
select new {
articleId = article.Attribute("ID").Value,
heading = article.Element("Heading").Value,
summary = article.Element("Summary").Value,
contents = article.Element("Contents").Value,
cats = from cat in article.Elements("Categories")
select new {
category = cat.Element("Category").Value
}
};
The problem is that article.Element("Summary") returns null if the element is not found, so you get a NullReferenceException when you try to get the Value property.
To solve this, note that XElement also has an explicit conversion to string. This won't throw if the XElement is null - you will just get a null string reference.
So to solve your problem you can change this:
summary = article.Element("Summary").Value,
to this:
summary = (string)article.Element("Summary")
Related
I have a big problem. My code:
TablePosition pos = (TablePosition)
tableView.getSelectionModel().getSelectedCells().get(0);
Object item = tableView.getItems().get(pos.getRow());
Object e = ((List<ObservableList>) item).get(0);
String new_status = "textExample";
and how can I use equals ? new_status.equals(e) ? I don't have any idea on how to convert this.
p.s. in console e = "textExample".
I need this to update a sql row.
If you want to get selected items, you can just use getSelectedItems() (or getSelectedItem() if you only want the latest selection). You don't need to work with selected cells, table positions and rows.
Assuming a TableView<ObservableList<String>> (which you may or may not have). Code to retrieve the value of the first element of the selected row (probably the value represented in the first column), would be as follows:
final String NEW_STATUS = "textExample";
final TableView<ObservableList<String>> tableView = new TableView<>();
final ObservableList<String> selectedItem =
tableView.getSelectionModel().getSelectedItem();
if (selectedItem != null
&& !selectedItem.isEmpty()
&& NEW_STATUS.equals(selectedItem.get(0))) {
// do work here.
}
As your type definitions may be different you may need to adapt the code above to fit your situation as required. If you still can't work it out, you will need to edit the question to provide an mcve to get further assistance.
Im having an issue with this , Im new to asp.net and really dont have much understanding with their syntax, I do understand the error but have no idea how to implement a fix:
ProductTable.RowFilter = "ProductID ='" & ddlCategory.SelectedValue & "'"
The error im recieving is : cannot perform '=' operation on system.int32 and system.string data view
my productID data type is : int;
Now i dont see how im comparing a string vs int, ddlCatergory selected index would also return a value... besides the point...im completely stuck.
any help is appreciated.
Using windows 8, VS 2012 , SQL database.
ddlCategory.SelectedValue is likely to be string given the SelectedValue attribute of the drop down list is a string, you are also assigning it as a string e.g. the filter value could end up being something like "ProductID ='123'" where 123 is the SelectedValue.
Assuming that SelectedValue is never null or empty I would use something like:
ProductTable.RowFilter = string.format("ProductID = {0}", ddlCategory.SelectedValue);
If it could be empty then I would do something along these lines:
if(string.IsNullOrEmpty(ddlCategory.SelectedValue))
{
ProductTable.RowFilter ="";
}
else {
ProductTable.RowFilter = string.format("ProductID = {0}", ddlCategory.SelectedValue);
}
OR
int tempInt;
if(int.TryParse(ddlCategory.SelectedValue,out tempInt))
{
ProductTable.RowFilter = string.format("ProductID = {0}", tempInt);
}
I've written the above in C# (not syntax checked though sorry!) though it would be easy enough to convert it to VB if necessary.
You should try by removing single quotes after = sign, so it give something like this
ProductTable.RowFilter = "ProductID = " + ddlCategory.SelectedValue
I have a label to show BookName. I get it from table which name tblBooks. I don't know how to show Book Name into the label.
var query = from b in dc.tblBooks.Where(b=>b.BookID == 'B01') select b;
Can you help me know.
Your query as written will return a collection of books—IQueryable<Book>. If you're sure there will only be one result in this query, you can call SingleOrDefault, which will execute the query immediately and give you the actual book.
var Book = dc.tblBooks.Where(b => b.BookID == 'B01').SingleOrDefault();
if (Book != null)
myLabel.Text = Book.BookName;
Or you can simply say:
var Book = dc.tblBooks.SingleOrDefault(b => b.BookID == 'B01');
Which does the same thing.
If you're 110% sure there will always be a result, and you don't want to check for null, then you can use Single, which will do the same thing, except throw an exception if no results are found, where SingleOrDefault simple returns null.
var Book = dc.tblBooks.Single(b=>b.BookID == 'B01');
myLabel.Text = Book.BookName;
Try:
label.Text = query.FirstOrDefault().BookName;
When i have a DataView Operation as
EnumerableRowCollection<DataRow> query
= from order in _table.AsEnumerable()
where order.Field<Int32>("key") > 2 && order.Field<Int32>("key") < 4
select order.Field<Int32>("key")=1000, order.Field<string>("name");
I can't form the above expression.
When i try
select new {key= 1000,name= order.Field<string>("name") };
i got
Cannot implicitly convert type
'System.Data.EnumerableRowCollection<AnonymousType#1>'
to 'System.Data.EnumerableRowCollection<System.Data.DataRow>'
How to form the right query? My task is to replace the key with 1000 and leave the name as is.
When you write select new {key= 1000,name= order.Field<string>("name") }, you're creating a new anonymous type that has nothing to do with DataRow.
Therefore, you can't assign it to a EnumerableRowCollection<DataRow>.
To fix the compiler error, change EnumerableRowCollection<DataRow> to var.
However, that won't fix your underlying problem.
LINQ cannot be used to modify data.
You need to use a normal foreach loop and set the key values, like this:
var affectedRows = from order in _table.AsEnumerable()
where order.Field<Int32>("key") > 2 && order.Field<Int32>("key") < 4
select row;
foreach(DataRow row in affectedRows) {
row["key"] = 1000;
}
This code will modify the original DataRows in the original _table.
If you don't want to modify the original _table, you can copy it by calling DataTable.Copy().
Look please below this codes throw me : FormatException was unhandled by user code
Codes:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
How can i rewrite linq query?
You are calling ToString on the query rather than a single result. Even though you may expect only one value to match your query, it will not return just a single value. You have to instruct it to do so using Single, First, Last or the variations of these that also return a default value (SingleOrDefault, FirstOrDefault, LastOrDefault).
In order to avoid an exception, you could change it to use Decimal.TryParse or you could change your code to use a default value if the LINQ query returns something that won't parse properly. I'd recommend the former or a combination.
Note that in the following example, I have added the call to SingleOrDefault. This ensures that only one value is parsed, even if no value is found, and that if there are multiple results, we get an exception (i.e. it enforces that we get exactly zero or one result to the query).
decimal parsedValue;
if (Decimal.TryParse(
genSatisctx
.Urun
.Where(o => o.ID == UrunID)
.Select(o=>o.Kdv)
.SingleOrDefault()
.ToString(), out parsedValue))
{
satis.KDV = parsedValue;
}
You're calling ToString() on an IQueryable<T> - what did you expect the string to be? It's very unlikely to be anything which can be parsed as a decimal number!
My guess is that you want to call First() or Single(), but we can't really tell without more information. What's the type of o.Kdv?
I suspect you either want:
satis.KDV = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
or
string kdvString = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
decimal kdv;
if (decimal.TryParse(kdvString, out kdv))
{
satis.KDV = kdv;
}
else
{
// What do you want to do if it's not valid?
}
When I use debug mode I see the data is update when over mouse, after end of this method ( it's show this message [input string was not in a correct format]
/* protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
SqlDataSource2.Update();
}
catch (Exception j)
{
j.Message.ToString();
}
}
/* }