I have a datagrid bound to a list of objects. Users can add a new row below where the cursor is ( In code I create a new object and insert it in the list at the appropiate position).
Imagine that the datagrid has 4 rows
If the cursor is positioned in row number 4, then the row gets added, however, if the cursor is position in any of the other rows (1,2 or 3) then I get this exception:
System.Windows.Markup.XamlParseException occurred
Message="Root element is missing."
Source="PresentationFramework"
LineNumber=0
LinePosition=0
StackTrace:
at System.Windows.Markup.XamlReaderHelper.RethrowAsParseException(String keyString, Int32 lineNumber, Int32 linePosition, Exception innerException)
InnerException: System.Xml.XmlException
Message="Root element is missing."
Source="System.Xml"
LineNumber=0
LinePosition=0
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Windows.Markup.XmlCompatibilityReader.Read()
at System.Windows.Markup.XamlReaderHelper.Read(XamlNode& xamlNode)
InnerException:
NOTE: when the app first loads, if i first add a row (by being in the last row), then i am also able to add a row from any of the other rows. However, if i first try to add a row from row numbers 1,2,3 then it fails!
Any help will be greatly appreciated. I am totally lost. I doubt anyone else has experienced this, but maybe you know what can be causing this or how I could debug it, as I do not know where to start :(
private void OnAddRowBelowCursor(DataGrid datagrid)
{
try
{
int index = datagrid.SelectedIndex;
MyObject newObj = new MyObject();
ObjectList.Insert(index + 1, newObj);
Logging.log.Info("Appended object row below the cursor...");
}
catch (Exception ex)
{
Logging.log.Error("Error appending row below cursor. Reason: " + ex.ToString());
}
}
private void OnAppendRowToBottom()
{
try
{
MyObject newObj = new MyObject();
ObjectList.Add(newObj);
Logging.log.Info("Appended object row to bottom...");
}
catch (Exception ex)
{
Logging.log.Error("Error appending row to the bottom of the table. Reason: " + ex.ToString());
}
}
I have also notice that adding a row to the bottom does not fail
Thanks
Looks like the data Your are loading is badly formatted. I may sugest You such a solution, which will allow you to parse any XML or HTML source even if it's fails the validation
I was using the RTB from the extended library with an XAMLFormatter.
When creating a new row, I wasn't converting my empty string to XAML fortmat. Why it only fails when I was adding it below the cursor and not at the end, I still do not know. But it is fixed
Related
I'm getting the error code SQLITE_BUSY when trying to write to a table after selecting from it. The select statement and result is properly closed prior to my insert.
If I'm removing the select part the insert works fine. And this is what I'm not getting. According to the documentation SQLITE_BUSY should mean that a different process or connection (which is definetly not the case here) is blocking the database.
There's no SQLite manager running. Also jdbcConn is the only connection to the database I have. No parallel running threads aswell.
Here's my code:
try {
if(!jdbcConn.isClosed()) {
ArrayList<String> variablesToAdd = new ArrayList<String>();
String sql = "SELECT * FROM VARIABLES WHERE Name = ?";
try (PreparedStatement stmt = jdbcConn.prepareStatement(sql)) {
for(InVariable variable : this.variables.values()) {
stmt.setString(1, variable.getName());
try(ResultSet rs = stmt.executeQuery()) {
if(!rs.next()) {
variablesToAdd.add(variable.getName());
}
}
}
}
if(variablesToAdd.size() > 0) {
String sqlInsert = "INSERT INTO VARIABLES(Name, Var_Value) VALUES(?, '')";
try(PreparedStatement stmtInsert = jdbcConn.prepareStatement(sqlInsert)) {
for(String name : variablesToAdd) {
stmtInsert.setString(1, name);
int affectedRows = stmtInsert.executeUpdate();
if(affectedRows == 0) {
LogManager.getLogger().error("Error while trying to add missing database variable '" + name + "'.");
}
}
}
jdbcConn.commit();
}
}
}
catch(Exception e) {
LogManager.getLogger().error("Error creating potentially missing database variables.", e);
}
This crashes on int affectedRows = stmtInsert.executeUpdate();. Now if I remove the first block (and manually add a value to the variablesToAdd list) the value inserts fine into the database.
Am I missing something? Am I not closing the ResultSet and PreparedStatement properly? Maybe I'm blind to my mistake from looking at it for too long.
Edit: Also executing the select in a separate thread does the trick. But that can't be the solution. Am I trying to insert into the database too fast after closing previous statements?
Edit2: I came across a busy_timeout, which promised to make updates/queries wait for a specified amount of time before returning with SQLITE_BUSY. I tried setting the busy timeout like so:
if(jdbcConn.prepareStatement("PRAGMA busy_timeout = 30000").execute()) {
jdbcConn.commit();
}
The executeUpdate() function still immedeiately returns with SQLITE_BUSY.
I'm dumb.
I was so thrown off by the fact that removing the select statement worked (still not sure why that worked, probably bad timing) that I missed a different thread using the same file.
Made both threads use the same java.sql.Connection and everything works fine now.
Thank you for pushing me in the right direction #GordThompson. Wasn't aware of the jdbc:sqlite::memory: option which led to me finding the issue.
can anybody tell me where I am doing wrong.I am trying to develop a small site on my own using c#.I am unable to show the record which was fetched from datareader.
{
SqlConnection cone = new SqlConnection("User id=...;Password=;...");
SqlCommand conecmd = new SqlCommand("select bankbalance from bank where bankpassword='" + txtboxbankpassword.Text + "'", cone);
cone.Open();
SqlDataReader drcone = conecmd.ExecuteReader();
if (drcone.HasRows) // says it has row(s) i.e., Hasrows=true
{
while (drcone.Read()) // here its value is false
{
lblremainingbankbalance.Text = drcone["bankbalance"].ToString();
}
int a;
a = Convert.ToInt32(lblremainingbankbalance.Text);
lblmsg.Text = "Transaction successful.Please wait while we redirect you to mypage and your current " + bankstore + " accountbalance is " + a + "";
Response.AddHeader("REFRESH", "5;URL=Mypage.aspx");
txtboxbankpassword.Text = "";
} else {
lblmsg.Text = "Norecord(s)";
}
}
Try to run your query in SQL server and see if it shows some rows because i don't see any errors in code also trim the text of your textbox like this
txtboxbankpassword.Text.Trim()
Also close you connection when you are done with reading rows from datareader.
your case is very strange.. if drcone.HasRowsis true drcone.Read() have to return true... minimum for one time..
Are you debugging the code and add drcone.Read() to quickwatch or have it in your watchlist? Because, then it will run the method Read() before your while loop. Next time when you call Read() (in your while-loop) it will return false..
You get one row, the reader aligns the reader to the first row (in whatchlist), and returns false in your while loop and saying "there are no rows left after this one".
See this link Here for the documentation on this: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx
if you have only a singlerow, the reader "is on position -1".. after drcone.Read() (return true) set the position to 0 (1 and last row).. next time you call drcone.Read() it will return false.. because there are no rows left after this one (reader is on position 0)
I tried group telerik grid using drop down list
grouping method source code is bellow
try
{
this.grd.MasterTableView.GroupByExpressions.Clear();//clear all group expressions
grd.MasterTableView.GroupsDefaultExpanded = false;
GridGroupByExpression expression = new GridGroupByExpression();
GridGroupByField gridGroupByField = new GridGroupByField();
gridGroupByField = new GridGroupByField();
if (cboGroupByItem1.SelectedValue != "0")
{
gridGroupByField.FieldName = cboGroupByItem1.SelectedValue;
gridGroupByField.HeaderText = cboGroupByItem1.SelectedItem.Text;
expression.SelectFields.Add(gridGroupByField);
}
if (cboGroupByItem2.SelectedValue != "0")
{
gridGroupByField.FieldName = cboGroupByItem2.SelectedValue;
gridGroupByField.HeaderText = cboGroupByItem2.SelectedItem.Text;
expression.SelectFields.Add(gridGroupByField);
}
grd.MasterTableView.GroupByExpressions.Add(expression);
}
catch (Exception ex)
{
label1.Text = ex.ToString();
}
finally
{
grd.Rebind();
}
when grid rebind method it will generate bellow error
An error occurred adding a relation to DataRelationCollection. Please,
make sure you have configured the expressions properly - both
GroupByFields and SelectFields are required!
How to solve this problem ?
You need to add this line after you add the gridGroupField to expression.
expression.GroupByFields.Add(gridGroupByField);
As the error message says, you need to add the fields you want to groupby.
If you have an aggregate field you dont have to add it to the expression as GroupByField, only as SelectFields.
Hope it helps.
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();
}
}
/* }
When the first cell of an excel sheet to import using ExcelStorage.ExtractRecords is empty, the process fail. Ie. If the data starts at col 1, row 2, if the cell (2,1) has an empty value, the method fails.
Does anybody know how to work-around this? I've tried adding a FieldNullValue attribute to the mapping class with no luck.
Here is a sample project that show the code with problems
Hope somebody can help me or point in some direction.
Thank you!
It looks like you have stumbled upon an issue in FileHelpers.
What is happening is that the ExcelStorage.ExtractRecords method uses an empty cell check to see if it has reached the end of the sheet. This can be seen in the ExcelStorage.cs source code:
while (CellAsString(cRow, mStartColumn) != String.Empty)
{
try
{
recordNumber++;
Notify(mNotifyHandler, mProgressMode, recordNumber, -1);
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
catch (Exception ex)
{
// Code removed for this example
}
}
So if the start column of any row is empty then it assumes that the file is done.
Some options to get around this:
Don't put any empty cells in the first column position.
Don't use excel as your file format -- convert to CSV first.
See if you can get a patch from the developer or patch the source yourself.
The first two are workarounds (and not really good ones). The third option might be the best but what is the end of file condition? Probably an entire row that is empty would be a good enough check (but even that might not work in all cases all of the time).
Thanks to the help of Tuzo, I could figure out a way of working this around.
I added a method to ExcelStorage class to change the while end condition. Instead of looking at the first cell for empty value, I look at all cells in the current row to be empty. If that's the case, return false to the while. This is the change to the while part of ExtractRecords:
while (!IsEof(cRow, mStartColumn, RecordFieldCount))
instead of
while (CellAsString(cRow, mStartColumn) != String.Empty)
IsEof is a method to check the whole row to be empty:
private bool IsEof(int row, int startCol, int numberOfCols)
{
bool isEmpty = true;
string cellValue = string.Empty;
for (int i = startCol; i <= numberOfCols; i++)
{
cellValue = CellAsString(row, i);
if (cellValue != string.Empty)
{
isEmpty = false;
break;
}
}
return isEmpty;
}
Of course if the user leaves an empty row between two data rows the rows after that one will not be processed, but I think is a good thing to keep working on this.
Thanks
I needed to be able to skip blank lines, so I've added the following code to the FileHelpers library. I've taken Sebastian's IsEof code and renamed the method to IsRowEmpty and changed the loop in ExtractRecords from ...
while (CellAsString(cRow, mStartColumn) != String.Empty)
to ...
while (!IsRowEmpty(cRow, mStartColumn, RecordFieldCount) || !IsRowEmpty(cRow+1, mStartColumn, RecordFieldCount))
I then changed this ...
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
to this ...
bool addRow = true;
if (Attribute.GetCustomAttribute(RecordType, typeof(IgnoreEmptyLinesAttribute)) != null && IsRowEmpty(cRow, mStartColumn, RecordFieldCount))
{
addRow = false;
}
if (addRow)
{
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
What this gives me is the ability to skip single empty rows. The file will be read until two successive empty rows are found