I have written a code to store uploaded image names into the session list.
A user can upload only 4 images, so there will be max 4 image names in a session.
A user can upload 1, 2, 3 or 4 images based on requirement. If a user selects only 2 images, the session will have only 2, so the rest 2 will throw index out of bound exception!
to handle such situation i have written following code.
string image1 = "";
string image2 = "";
string image3 = "";
string image4 = "";
var imageSessList = (List<string>)Session["Images"];
if (imageSessList != null)
{
for (int i = 0; i < imageSessList.Count; i++)
{
if (imageSessList[i] != null && i == 0)
{
image1 = imageSessList[i];
}
if (imageSessList[i] != null && i == 1)
{
image2 = imageSessList[i];
}
if (imageSessList[i] != null && i == 2)
{
image3 = imageSessList[i];
}
if (imageSessList[i] != null && i == 3)
{
image4 = imageSessList[i];
}
}
}
But now it's showing following error: "Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List"
How can I resolve it, or is there any way to complete this functionality.
The problem is that Session["Images"] doesn't contain a list but a string. You have to correct this on the setting side.
A general solution to prevent such errors is by wrapping the session state into a class, and using the typed properties from that class for getting and setting:
public static class SessionState
{
public List<string> Images
{
get
{
return HttpContext.Current.Session["Images"] as List<string>;
}
set
{
HttpContext.Current.Session["Images"] = value;
}
}
}
Now you can just get and set SessionState.Images.
From previously mentioned comments:
#StephanBauer i have written following lines in foreach: lstImageNames.Add(destFileName); context.Session["Images"] = lstImageNames; – ace 22 mins ago
If context.Session["Images"] = lstImageNames; is done in foreach loop, then you are overwriting the value in the session each time.
One more thing i wanted to point out is, string can not only be null but empty too. So, you may want to change your null checks as (just a suggestion):
if (!string.IsNulOrEmpty(imageSessList[i])l && i == 0)
Related
I got the following code:
//getting skills from DB
var skills = this.db.HumanSkills.Where(r => r.HumanId == model.Id).Include(x => x.Skill).ToList();
for (int i = 0; i < model.Skills.Count; i++) //iterating over the list. Boundary set to i < model.Skills.Count this is number of elements in my viewmodel (model.Skills) using which I am going to update Name property of my DB elements.
{
if (skills[i] != null) //index out of range here. Why?
{
//here I update DB skill names using model skill names
skills[i].Skill.Name = model.Skills[i].Skill.Name;
}
else //here I create new Skill for every element of the DB skill list that doesn't exist
{
var newSkill = new HumanSkill { Skill = model.Skills[i].Skill, Human = currentHuman };
this.db.Add(newSkill);
this.db.SaveChanges(); //yes, I know it's not a good practice to execute it each time, but otherwise rows in my HumanSkills table are not sorted.
}
}
On line:
if (skills[i] != null) //index out of range here. Why?
I am getting index out of range, even though I use !=null
It seems to me that var skills is a different object than model.Skills
"var skills" and "model.Skills" are 2 different variables.
There are of the same type, but it's 2 differents objects!
You can do that :
IEnumerable<Skill> skillsList = this.db.HumanSkills.Where(r => r.HumanId == model.Id).Include(x => x.Skill).ToList();
foreach (Skill s in skillsList)
{
// your logic... or debug.print for check how many items are get from the db
}
I try to add image to my first column(it might be change to another column later, it's in first column for now), so far I have do
if (item.Index == 0)
{
item.ImageGetter = delegate (object RowObj)
{
return ((RowObjectModel)RowObj).ImageToShow.ToString();
};
}
this part at start, I use a custom headerstyle and apply it on constructor while I do that I also do ImageGetter part. I also set my SmallImageList like this
ImageList IList = new ImageList();
IList.Images.Add("MyIcon", Properties.Resources.MyIcon);
mainForm.objListview.SmallImageList = IList;
I have 2 problems with this code, first I can't set my image. It's not showing on my listview.
What I do to achieve that is this :
(objListview.GetItem(z).RowObject as RowObjectModel).ImageToShow = ThumbnailImages.MyIcon;
my enum is like this :
public enum ThumbnailImages
{
NULL = 0,
MyIcon = 1,
MyIcon2 = 2,
MyIcon3 = 3,
MyIcon4 = 4,
MyIcon5 = 5
}
Second problem is I have literally no clue on how I can add a second image in the same column of same row. I'm not even sure if this is possible.. But I have to do it somehow so I'm open to any ideas.
EDIT :
Okay I found the solution to my first problem. I was not using the UpdateObject/UpdateObjects method. I marked all my items with proper images they should show and use this method and everything worked. Now all I need is to find a way to show 2 images at the same time in 1 cell.
EDIT 2 :
About my second problem I found this class --> ImagesRenderer
http://objectlistview.sourceforge.net/cs/ownerDraw.html#imagesrenderer
But I could not found any working solution so far and I don't have any clue on how this is working?
Now all I need is to find a way to show 2 images at the same time in 1 cell.
You can work around the requirement to show 2 images by showing 1 image that contains both. The example below does that. One note is that you should probably build a cache up front of all the combinations so you can return them at high speed rather than building them in the ImageGetter delegate
olv.ShowGroups = false;
//make 2 images
var img1 = new Bitmap(10, 10);
var g = Graphics.FromImage(img1);
g.FillRectangle(new SolidBrush(Color.Pink),2,2,8,8 );
var img2 = new Bitmap(10, 10);
var g2 = Graphics.FromImage(img2);
g2.FillRectangle(new SolidBrush(Color.Blue),2,2,8,8 );
var col1 = new OLVColumn();
col1.AspectName = "ToString";
col1.ImageGetter += delegate(object rowObject)
{
if(rowObject == "1")
return img1;
if(rowObject == "2")
return img2;
if (rowObject == "3")
{
var comboImg = new Bitmap(img1.Width + img2.Width, img1.Height + img2.Height);
using (var g3 = Graphics.FromImage(comboImg))
{
g3.DrawImage(img1,new Point(0,0));
g3.DrawImage(img2,new Point(img1.Width,0));
}
return comboImg;
}
return null;
};
olv.Columns.Add(col1);
olv.AddObject("1");
olv.AddObject("2");
olv.AddObject("3");
}
The solution I found thanks to #Thomas N was this --->
In my objectlistview initializer I did this :
item.Renderer = new ImageRenderer();
item.AspectGetter = delegate (object RowObj)
{
return ((RowObjectModel)RowObj).ImagesToShow;
};
item represent here column 0. I'm iterating all my columns to apply HeaderFormatStyle. I figure I could do this here too.
and before I do this initializer I also set my images
ImageList IList = new ImageList();
IList.Images.Add("NULL", Properties.Resources.Null);
IList.Images.Add("MyIcon", Properties.Resources.MyIcon);
IList.Images.Add("MyIcon2", Properties.Resources.MyIcon2);
IList.Images.Add("MyIcon3", Properties.Resources.MyIcon3);
IList.Images.Add("MyIcon4", Properties.Resources.MyIcon4);
IList.Images.Add("MyIcon5", Properties.Resources.MyIcon5);
objListview.SmallImageList = IList;
and all I have to do is calling my method I wrote inside my model class
public void AddThumbnailImage(ThumbnailImages tImage)
{
if (tImage == ThumbnailImages.NULL)
{
ImagesToShow.Clear();
}
else
{
if (!ImagesToShow.Contains((int)tImage))
ImagesToShow.Add((int)tImage);
}
}
I know my solution is very similar to yours Thomas but I just wanted to show how I did it :)
My app is crashing after I clear the Bing Map of its pushpins and then open a flyout. This is what I see in the debugger:
The textblock is definitely not null - it is defined declaratively in XAML.
The List of String (CurrentlyMappedPhotosets) is not null - as you can see, it contains a string / has a count of 1.
The code just before what's seen on the scream shot is:
int count = App.CurrentlyMappedPhotosets.Count;
What could be null here?
Just before this happens, I call ClearMap:
private void ClearMap()
{
var mapLayerChildren = from c in DataLayer.Children select c;
var kinderGarten = mapLayerChildren.ToArray();
for (int i = 0; i < kinderGarten.Count(); i++)
{
if (kinderGarten[i] is Pushpin)
{
DataLayer.Children.Remove(kinderGarten[i]);
}
}
CloseInfobox();
App.CurrentlyMappedPhotosets.Clear();
if (null != App.photosetLocationCollection)
{
App.photosetLocationCollection.Clear();
}
appbarbtnClearMap.IsEnabled = false;
UpdateGUI(false);
}
...which calls UpdateGUI():
private void UpdateGUI(bool resizeMap)
{
appbarbtnRenamePhotoset.IsEnabled = App.CurrentlyMappedPhotosets.Count > 0;
if (resizeMap)
{
ResizeMap();
}
}
Have you looked if the value present in the collection is not null?
Any non primitive type class is by default null if not constructed with a value.
So you can have as many null values of the type you are trying to have.
I suggest that you do a test by changing the line to:
textblock0.Text = App.CurrentlyMappedPhotosets[0].HasValue ? App.CurrentlyMappedPhotosets[0].Value : "";
I am trying to check that an item doesn't already exist in a list box before I add the new item.
if (TeamNameTextBox.Text != "")
{
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)
{
TeamNameListBox.Items.Add(TeamNameTextBox.Text);
TeamNameTextBox.Text = "";
int teamCountUpdate = TeamNameListBox.Items.Count;
if (teamCountUpdate == 1)
{
TeamCount.Text = teamCountUpdate.ToString() + " Team";
}
else
{
TeamCount.Text = teamCountUpdate.ToString() + " Teams";
}
}
else
{
AddTeamSeasonError.Text = "This team has already been added";
}
}
else
{
AddTeamSeasonError.Text = "Please select a team";
}
I have got it to check if the text box is blank, but I need to check that the item a user is trying to add is not already in the the list box.
I have tried the line:
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)
But that doesn't work, any suggestions on how I can do the check?
Use this:
if (!TeamNameListBox.Items.Contains(TeamNameTextBox.Text))
TeamNameListBox.Items.Add(TeamNameTextBox.Text);
think you should at least try to use TeamNameTextBox instead of TeamNameListBox as argument
if (TeamNameListBox.Items.FindByValue(TeamNameTextBox.Text) == null)
I suppose you mean
// search if the textbox value is found in the list. this comment shouldn't be part of the code
if (TeamNameListBox.Items.FindByValue(TeamNameTextBox.Text) == null)
instead of
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null) // code from question
EDIT: There is no need to put the name of the type of the control next to the variable.
i.e. instead of TeamNameListBox, use teamNames. And, instead of TeamNameTextBox, use teamName.
I am using C# to create a Silverlight 4 application.
I am trying to do the following:
MapNode endNode = null;
if (keyword != null && keyword != "")
{
EntityQuery<NodeIDProj> res = CampusQueries.getNodeIDByNameQuery(keyword);
var queryres = CampusQueries.Load<NodeIDProj>(res, (items) =>
{
foreach (var item in items.Entities)
{
MapNode n = mapHelp.getNodeByID(item.NodeID);
if (n != null)
{
endNode = n;
TrackAnimation();
}
}
}, true);
}
However, after this point, my variable endNode is still null. TrackAnimation() works as though endNode has a valid value, but outside of the Load statement, endNode is back to null.
I know that I am lacking in understanding of how this works, and I would really appreciate an help given.
What I am trying to do, is query my database and I want to use those results in other methods rather than displaying them in a datagrid.
I want endNode to have value which I can use in other methods.
Please help me to figure out a way to do this, thank you!
EDIT:
Thank you, SLaks
Can I do something like:
MapNode endNode = null;
if (keyword != null && keyword != "")
{
EntityQuery<NodeIDProj> res = CampusQueries.getNodeIDByNameQuery(keyword);
var queryres = CampusQueries.Load<NodeIDProj>(res, (items) =>
{
foreach (var item in items.Entities)
{
MapNode n = mapHelp.getNodeByID(item.NodeID);
if (n != null)
{
endNode = n;
TrackAnimation();
}
}
}, true);
}
queryres.Completed += new EventHandler(queryres_Completed);
void queryres_Completed(object sender, EventArgs e)
{
//stuff
}
If so, how can I get access to the endNode variable, as it is declared within another method?
Your Load method is probably asynchronous, meaning that the callback happens some time after the rest of your code runs.
You can only use the result after you actually receive it.