listbox and search returning null - c#

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.

Related

How To Get Values From Cells In Radgrid C# asp.net

I am trying to get specific cell value so i can pass it in my method when i press the button but i get always null on both (and i know that is not null).
P.s: None row is selected because i made a loop to get all the rows. The variable "p" is getting correct the number of the rows that i have on the grid.
protected void PostRadButton_Click(object sender, EventArgs e)
{
int p;
if (DocStatTxtBox.Text == "2")
{
foreach (GridDataItem item in RadGrid1.Items)
{
p = item.RowIndex;
string itemcodeparam = item["ItemCode"].Text;//error null (4th cell)
int quantityparam = Convert.ToInt16(item.Cells[5].Text);//error null
Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue,itemcodeparam,-quantityparam);
}
}
}
Finally i did it with this code
protected void PostRadButton_Click(object sender, EventArgs e)
{
int p;
if (DocStatTxtBox.Text == "2")
{
foreach (GridDataItem item in RadGrid1.Items)
{
p = item.RowIndex;
Label itemparam = (Label)item["ItemCode"].FindControl("ItemCodeLabel");
Label qparam = (Label)item["Quantity"].FindControl("QuantityLabel");
string itemcodeparam = itemparam.Text;
int quantityparam = Convert.ToInt16(qparam.Text);
Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue, itemcodeparam, -quantityparam);
}
}
}

Maintaining session object in webforms

What I am attempting to do is preserve a session object that stores a Dictionary .
I need this dictionary in order to keep a running list that matches up to an asp:Gridview.
Every time the page loads, I'm checking the Dictionary and highlighting any matches in the Gridview.
However, every time Page_Load occurs, the Session["Rolls"] is coming up as null. Now, I'm also highlighting matching entries in a buttonClick event and the Dictionary is preserved up until I initiate a different event (like another button click OR GridView_RowEditing/GridView_RowUpdating). Are there any principals of Session variables that I'm not paying attention to?
Google Chrome console also recognizes the Session throughout every action, but in Debug, every Page_Load brings up a null Session["Rolls"].
Here's my Page_Load code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["Rolls"] = new Dictionary<string, int>();
}
else
{
WoSource.SelectCommand =
"SELECT WorkOrderNo, RollNumber, ModelNumber, QtyGood, QtyRun FROM RFID_Inventory WHERE WorkOrderNo= '" + woText.Text + "'";
var currentDict = (Dictionary<string, int>) Session["Rolls"];
if (currentDict == null)
{
}
else
{
foreach (var entry in currentDict)
{
foreach (GridViewRow row in GridView1.Rows)
{
var dataKey = GridView1.DataKeys[row.RowIndex];
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 0))
{
row.BackColor = System.Drawing.Color.Red;
break;
}
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 1))
{
row.BackColor = System.Drawing.Color.Green;
break;
}
}
}
}
}
}
EDIT: Discovered that the RowEditing/RowUpdating events are not preserving the GridView Backcolor highlighting that I'm doing.
Is there something I can add to those event calls?
Here is my RowEditing event:
protected void GridView1_RowEditing(object sender, EventArgs e)
{
var currentDict = (Dictionary<string, int>)Session["Rolls"];
if (currentDict == null)
{
}
else
{
foreach (var entry in currentDict)
{
foreach (GridViewRow row in GridView1.Rows)
{
var dataKey = GridView1.DataKeys[row.RowIndex];
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 0))
{
row.BackColor = System.Drawing.Color.Red;
break;
}
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 1))
{
row.BackColor = System.Drawing.Color.Green;
break;
}
}
}
}
}
EDIT2: My issue was solved. My session wasn't coming back null. I actually needed to add my GridView highlighting method to the GridView_RowDataBound event. Turns out I was just trying to highlight the gridview at the wrong time. I marked the Kishore's answer as correct so that users can see my reply. Thanks for everybody's help.
As i look your code you are initialize session variable on page load so you lost the state. you can put a null check before initialize session variable.
Well What we do for managing our Global Object into session is Encapsulating them in Property. Lets have a look in this:
public Dictionary<string, int> Rolls
{
get
{
if(Session["Rolls"] == null)
return new Dictionary<string, int>();
else
return (Dictionary<string, int>)Session["Rolls"];
}
set
{
Session["Rolls"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Now Accessing Rolls in page will be directly hitting Session.
// and Get property will give New dictionary object with 0 record instead of null
// Otherwise it will return Object already caste into dictionary object
foreach (var entry in Rolls)
{
}
// We always can assign new Dictionary object in Session by
Rolls = new Dictionary<string, int>(10); // for example dictionary with 10 items
}
So we can use our Get Set in Parent class of Web page to make it accessible on all child classes. We can use similar approaches for View state and Cache objects as well.
Let me know if you have any question.

What is this ArgumentOutOfRangeException caused by?

I have a problem that drives me nuts. I am using a generic List that throws an ArgumentOutOfRangeException whenever I try to assign its first (or last?) index to a variable. It's a pretty large pile of code, hence I'll try to extract only the relevant stuff. So here it is:
private string GetRuleByName(string name, List<string> rules)
{
if(rules != null)
{
List<string> todo = new List<string>();
todo.AddRange(rules);
while(rules.Count != 0)
{
string r = todo[0]; // <- Error 'ArgumentOutOfRangeException' here
todo.RemoveAt(0);
// ...
}
}
}
That's how I call the method:
void treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
string currentRule = GetRuleByName(treeView.SelectedNode.FullPath, ruleCollection)
// the string list "ruleCollection" always contains
// strings and thus is never empty
}
Even though it's not a very detailed presentation of what's going on, as I had to cut off a piece of some complicated code, I really hope someone else might see what produces the error.
Big thanks in advance for at least having a look!
EDIT:
This is how the method looks like. I haven't altered anything, to show what's really inside it. I hope it makes sense for somebody:
private Rule GetRuleByNameOrId(string stName, List<Rule> rules)
{
if(rules != null)
{
string searchName = stName.ToLower().Trim();
string subName = "";
int slashPos = searchName.IndexOf('/');
if(slashPos != -1)
{
if(slashPos != searchName.Length)
subName = searchName.Substring(slashPos + 1);
searchName = searchName.Substring(0, slashPos);
}
List<Rule> todo = new List<Rule>();
todo.AddRange(rules);
while(todo.Count != 0)
{
Rule r = (Rule)todo[0];
todo.RemoveAt(0);
if(r.Name.ToLower() == searchName || r.Id.ToLower() == searchName)
{
if(subName != "")
{
Rule subRule = GetRuleByNameOrId(subName, r.Children);
if(subRule != null)
return subRule;
}
else
{
return r;
}
}
if(r.Children != null && r.Children.Count != 0)
todo.AddRange(r.Children);
}//end while
}//end if(rules != null)
return null;
}
Sounds like you want the following:
private string GetRuleByName(string name, List<string> rules)
{
if(rules != null)
{
List<string> todo = new List<string>();
todo.AddRange(rules);
while(todo.Count != 0) // <-- Minor mod here
{
string r = todo[0];
todo.RemoveAt(0);
// ...
}
}
}
Otherwise you are infinitely looping on rules.Count as the size of rules is not changing
This works fine until todo is empty, then you get the exception because element 0 no longer exists as you've removed them all!
Are you sure you don't want this instead:
while(rules.Count != 0)
{
string r = rules[0]; // <- Error 'ArgumentOutOfRangeException' here
rules.RemoveAt(0);
?
The way you've written it now, you've got a loop that would actually be infinite, except that you eventually remove all the elements from the todo list, at which point you throw the exception (because in an empty list even the 0-th element doesn't exist).

c# winform Invoke throws NullReferenceException

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

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