c# winform Invoke throws NullReferenceException - c#

i'm working on an winform(mdi) pro. And I need to update a dataGridView control when i get new data from another thread. and when new data comes and i'm dragging the dataGridview scroll, it throw a nullreference exception in dataGridView.Invoke. i have searched for few days and drove google crazy,but didn't help.
the code like this:
public void ReceiveNewData(object sender, UpateEventArgs ex)
{
if (this.dataGridView.InvokeRequired)
{
dataGridView.Invoke(new UpateEventHandler(ReceiveNewData), new object[] { this, ex });
}
else
this.BindNewData();
}
private void BindNewData()
{
if (dataGridView!= null && (QuoteMember.listOneClickQuoteItem != null || QuoteMember.listMarketingQuoteItem != null))
{
DataTable dataSource = PublicFunction.ToDataTable(QuoteMember.listOneClickQuoteItem);
if (dataSource != null)
dataSource.Merge(PublicFunction.ToDataTable(QuoteMember.listMarketingQuoteItem), true);
else
dataSource = PublicFunction.ToDataTable(QuoteMember.listMarketingQuoteItem);
dataGridView.DataSource = dataSource;
}
}
public PublicFunction
{
public static DataTable ToDataTable(List dataSource)
{
if(dataSource != null)
return ToDataTable((dataSource.ToArray()), 1);
return null;
}
public static DataTable ToDataTable(List dataSource)
{
if (dataSource != null)
return ToDataTable((dataSource.ToArray()), 2);
return null;
}
private static DataTable ToDataTable(QuoteItemBase[] m, int type)
{
DataTable dsTemp = null;
if (type == 1)
{
dsTemp = new DataTable("OneClickQuote");
}
else if (type == 2)
{
dsTemp = new DataTable("MarketingQuote");
}
else
dsTemp = new DataTable("temptable");
dsTemp.Columns.Add("Date");
dsTemp.Columns.Add("Time");
dsTemp.Columns.Add("NO");
dsTemp.Columns.Add("Name");
if (m == null)
return dsTemp;
foreach (var item in m)
{
DataRow drTemp = dsTemp.NewRow();
drTemp["Date"] = item.date;
drTemp["Time"] = item.time;
drTemp["NO"] = item.no;
drTemp["Name"] = item.name;
dsTemp.Rows.Add(drTemp);
}
return dsTemp;
}
}
PS:
if new data comes and i'm not dragging scroll bar, it works fine.
any ideas?
thank you !

I found that when you invoke a control and set bindings (or clear them)
and an object is set to null this can throw a null reference exception, this is reflected through invoke giving an error, this error however is somewhere else in your code:
quick example:
public class test : Form
{
public test()
{
Thread t = new Thread(start);
t.Start();
}
public void start()
{
LoadCompleteEvent();
}
public void LoadComplete() //fired by LoadCompleteEvent();
{
if(this.InvokeIsRequired)
{
//do invoke
//and return
}
comboBoxEditBrand.Properties.Items.Clear();
comboBoxEditBrand.Properties.Items.AddRange(ListOfStuff.ToArray());
}
public void comboBoxEditBrand_SelectedItemChanged(object sender, eventargs e) // fired as control is changed
{
//error here!!
if(comboBoxEditBrand.SelectedItem == SomeBrandItem) //<- this is where the error is thrown!! check for null first!
{
//do something
}
}
}
it's something like this.. this code will probably not throw the error because A) it's from the top of my head and B) it's made up. BUT this is kind of what bugged me for half a morning as to WHY this error was thrown.
just place
if(comboBoxEditBrand.SelectedItem == null)
return;
where it says //error here!! and it should work again.

Make sure you switch to the Gui thread before you invoke

Related

listbox and search returning null

I have a search function which works good the first time i run it. When i try adding a new search the program shuts down giving me the error message:
"markerat = listBoxSökResultat.SelectedItem.ToString().ToLower(); Object reference not set to an instance of an object. NullReference.
Ive tried using if and return; but that doesnt seem to help. Anyone knows whats wrong here?
private void buttonSökNamn_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
var v = (from x in el.Descendants("recept")
where x.Element("namn").Value.ToLower().Contains(textBoxNamn.Text.ToLower())
select x);
if (v == null)
{
MessageBox.Show("Finns inte!");
return;
}
foreach (var item in v.Elements("namn"))
{
Sökresultat.Add(item.Value);
}
listBoxSökResultat.DataSource = null;
listBoxSökResultat.DataSource = Sökresultat;
}
private void listBoxSökResultat_SelectedIndexChanged(object sender, EventArgs e)
{
string markerat;
markerat = listBoxSökResultat.SelectedItem.ToString().ToLower();
if (markerat == null) return;
listBox1.Items.Clear();
if (listBoxSökResultat.SelectedItems.Count == 0) return;
var v = (from x in el.Descendants("recept")
where x.Element("namn").Value.ToLower() == markerat
select x).FirstOrDefault();
if (v == null)
{
MessageBox.Show("Finns inte!");
return;
}
textBoxNamn.Text = v.Element("namn").Value;
listBox1.Items.Add(v.Element("portioner").Value);
var test = v.DescendantsAndSelf("ingrediens").ToList();
foreach (var item in test)
{
listBox1.Items.Add(item.Value);
}
var test2 = v.DescendantsAndSelf("steg").ToList();
foreach (var item in test2)
{
listBox1.Items.Add(item.Value);
}
}
listBoxSökResultat.SelectedItem is what is null, so any further calls (.ToString()) will cause that exception. You are currently checking it's not null and SelectedItems has a count higher than 0, but after the problem occurs. By then it's too late. That defensive checking is great, but you are doing it a little too late.
SelectedItem will be null if there is no selected item at the time, so you should check that first:
if (listBoxSökResultat.SelectedItem != null)
{
markerat = listBoxSökResultat.SelectedItem.ToString().ToLower();
}
That will let you pass this particular problem.

update the datagridview combobox, throws "Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function."

when i try to update the content of the datagridview combo box it throws
Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function
at line ,node.Cells[(int)Parameters.eColumn.valueBySelectionColumn] = cboCell;
How can i solve this problem??
THX
private void treeGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
if (e.Control.GetType() == new DataGridViewComboBoxEditingControl().GetType())
{
if ((cboEditor != null) && (cboEditor_EventHandler != null))
{
cboEditor.SelectedIndexChanged -= cboEditor_EventHandler;
}
cboEditor = (DataGridViewComboBoxEditingControl)e.Control;
cboEditor.SelectedIndexChanged += cboEditor_EventHandler;
if (this.treeGridView1.SelectedCells.Count > 0 &&
this.treeGridView1.SelectedCells[0].ColumnIndex == (int)Parameters.eColumn.valueBySelectionColumn)
{
TreeGridNode node = GetCurrentNode();
object cellValue = node.Parent.Cells[(int)Parameters.eColumn.sectionTypeColumn].Value;
Parameters.eSection section = (Parameters.eSection)dicSection[cellValue.ToString()];
this.treeGridView1.Focus();
switch (section)
{
case Parameters.eSection.UNIX_Script:
DataGridViewComboBoxCell cboCell = Parameters.ValidateChoice(Parameters.eSection.UNIX_Script,
node.Cells[(int)Parameters.eColumn.parameterTypeColumn].Value,
ref cboEditor);
if (cboCell != null)
{
***node.Cells[(int)Parameters.eColumn.valueBySelectionColumn] = cboCell;***
node.Cells[(int)Parameters.eColumn.valueBySelectionColumn].Style.BackColor =
node.Cells[(int)Parameters.eColumn.sequenceColumn].Style.BackColor;
}
break;
}
}
}
}
}

Getting NullReferenceException don't know why

I wasn't the one who coded this line of code, and I can't gt to understand whoever did it, why did this way on this line: res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper()).Value[i["LocaleID"].ToString()] = i["Value"].ToString();
And this line gives me a NullReferenceException. How can I get around it?
public static void LoadData(Value.Item _res)
{
DataTable Res = Connector.Run("SELECT * FROM Data WHERE ItemID='" + _res.ID + "'");
if (Res.Rows.Count != 0)
{
foreach (DataRow i in Res.Rows)
{
try
{
_res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper()).Value[i["LocaleID"].ToString()] = i["Value"].ToString();
}
catch (Exception)
{
_res.Data.Add(new Value.Data(
i["ID"].ToString(),
i["Value"].ToString(),
i["LocaleID"].ToString(),
i["MetaDataID"].ToString()
));
}
}
}
}
Thx a lot guys!!! Here is my working solution which hrows no Exceptions anymore!
public static void LoadData(Value.Item _res)
{
DataTable Res = Connector.Run("SELECT * FROM Data WHERE ItemID='" + _res.ID + "'");
if (Res.Rows.Count != 0)
{
foreach (DataRow i in Res.Rows)
{
bool _flagged = false;
var _result = _res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper());
if(_result != null && i["LocaleID"] != null)
{
if (i["Value"] == null || i["LocaleID"] == null || i["MetaDataID"] == null)
_flagged = true;
}
else
{
_flagged = true;
}
if (_flagged)
{
_res.Data.Add(new Value.Data(
i["ID"].ToString(),
i["Value"].ToString(),
i["LocaleID"].ToString(),
i["MetaDataID"].ToString()
));
}
//try
//{
// _res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper()).Value[i["LocaleID"].ToString()] = i["Value"].ToString();
//}
//catch (Exception)
//{
// _res.Data.Add(new Value.Data(
// i["ID"].ToString(),
// i["Value"].ToString(),
// i["LocaleID"].ToString(),
// i["MetaDataID"].ToString()
// ));
//}
}
}
}
Impossible to answer accurately without having the code under the debugger, however what is certain is that at least one of the following has a value of null:
_res.Data
itm.Meta
itm.Meta.ID
i["MetaDataID"]
i["LocaleID"]
i["Value"]
Old-skool debugging:
Break the statement down to it's consituent parts - using local variables. Step-through and find which one is null.
Check if one of the following are null:
i["MetaDataID"]
i["LocaleID"]
i["Value"]

Cannot attach an entity that already exists

I get this error whenever i try to update one of my models. The update is pretty simple:
Todo bn = service.GetTodos().Single(t => t.todoId == 1);
bn.Note.noteTitle = "Something new";
service.SaveTodo(bn);
And the models have this kind of structure:
A Todo has a Note
A Todo has a list of Tasks
I have my service's SaveTodo look a little something like this:
public void SaveTodo ( TodoWrapper note )
{
using (Repository repo = new Repository(new HpstrDataContext()))
{
if (note != null)
{
Todo todo = repo.Todos.SingleOrDefault(t => t.todoId == note.todoId);
if (todo == null)
{
todo = new Todo();
todo.Note = new Note();
}
todo.dueDate = note.dueDate;
todo.priority = (short)note.priority;
todo.Note.isTrashed = note.Note.isTrashed;
todo.Note.permission = (short)note.Note.permission;
todo.Note.noteTitle = note.Note.noteTitle;
repo.SaveTodo(todo);
}
}
}
And the Repository's SaveTodo method is pretty simple and looks like this:
public void SaveTodo ( Todo todo )
{
if (todo.Note.noteId == 0)
{
dc.NoteTable.InsertOnSubmit(todo.Note);
} else
{
dc.NoteTable.Attach(todo.Note);
dc.NoteTable.Context.Refresh(RefreshMode.KeepCurrentValues , todo.Note);
}
if (todo.todoId == 0)
{
dc.TodoTable.InsertOnSubmit(todo);
} else
{
dc.TodoTable.Attach(todo);
dc.TodoTable.Context.Refresh(RefreshMode.KeepCurrentValues , todo);
}
dc.SubmitChanges();
}
The error is being thrown at this line in the Repository: dc.NoteTable.Attach(todo.Note);. I've tried a lot of different things to get this to work but nothing seems to work.
Any help would be greatly appreciated
So i solved the problem (hopefully). In my Repository, i changed the SaveTodo to look like this
public void SaveTodo ( TodoWrapper note )
{
using (Repository repo = new Repository(new HpstrDataContext()))
{
if (note != null)
{
Todo todo = repo.Todos.SingleOrDefault(t => t.todoId == note.todoId);
if (todo == null)
{
todo = new Todo();
todo.Note = new Note();
}
todo.dueDate = note.dueDate;
todo.priority = (short)note.priority;
todo.Note.isTrashed = note.Note.isTrashed;
todo.Note.permission = (short)note.Note.permission;
todo.Note.noteTitle = note.Note.noteTitle;
foreach (TaskWrapper item in note.Tasks)
{
Task t = repo.Tasks.SingleOrDefault(task => task.tasksId == item.taskId);
if (t == null)
{
t = new Task();
}
t.Todo = todo;
t.isCompleted = item.isCompleted;
t.content = item.content;
repo.SaveTask(t);
}
}
}
}
If anybody was wondering, the wrappers are used as wrappers (no way) for the entities with wcf.
And my save task looked like this:
public void SaveTask ( Task task )
{
if (task.tasksId == 0)
{
dc.TaskTable.InsertOnSubmit(task);
} else
{
dc.TaskTable.Context.Refresh(RefreshMode.KeepCurrentValues , task);
}
dc.SubmitChanges();
}
I got rid of the Attach because I already pull out the Todo when calling the single or default statement so it was already attached to the database. So the error was correct because this entity was already attached to the database.
If i had made a new Todo instead of grabbing the one out the database, the attach would have worked. Hope this helps out anyone who stumbles upon this

Null Reference in editing a task scheduler trigger in c#

if (t != null) is always null why help..
when ever i try to get value in the variable name t it always gets in the else part but i am sure that there is valuse in tat variable.
private void button3_Click(object sender, EventArgs e)
{
try
{
if (search=="")
{
}
else
{
if (textBox1.Text=="")
{
MessageBox.Show("Select A Task Or Find One");
}
else
{
search = textBox1.Text;
}
}
if (search != null)
{
t = tasks.OpenTask(search);
if (textBox2.Text!="")
{
short hour = short.Parse(textBox2.Text.Substring(0, 2));
short minute = short.Parse(textBox2.Text.Substring(3, 2));
if (t != null) // this is null dont know why
{
foreach (Trigger tr in t.Triggers)
{
if (tr is StartableTrigger)
{
(tr as StartableTrigger).StartHour = hour;
(tr as StartableTrigger).StartMinute = minute;
}
}
t.Save();
t.Close();
}
tasks.Dispose();
button2.Visible = true;
textBox3.Visible = true;
search = "";
}
else
{
MessageBox.Show("Enter Time ");
}
}
}
catch (Exception b)
{
MessageBox.Show(b.ToString());
// MessageBox.Show("Select A Task From The List ");
}
}
help guys .. well i tried it to debug but didnt get a break through..
t is null because tasks.OpenTask(search) returns null.
Probably there is no task matching your search criteria.
Why are you disposing of tasks in the first place?
Any place in your source ,where you have written something like this MyClass t = new MyClass().. where t is your class object. If you have not declared,It will always come null.
Or might be you have declared something like this
private Task t; but forgot to add new keyword. Checkout!!!

Categories