I am trying to make a tabbed browser code sample, but I am having trouble implmeneting the solution correctly. I have created a custom class BrowserItem which has two values, my custom web browser and a url string. I then created an ObservableCollection of type BrowserItem, in which I add new items to the ObservableCollection on a click event. For some reason though, when I call my ShowTab method in my MainPage to show the web browser instance that the user selects (from a ListBox populated by the ObservableCollection), I am getting an ArgumentOutOfRange exception. To illustrate, what I have so far is as follows:
BrowserItem.cs
public FullWebBrowser browser
{
get;
set;
}
public string url
{
get;
set;
}
Settings.cs
public static Setting<ObservableCollection<BrowserItem>> Browsers = new Setting<ObservableCollection<BrowserItem>>("Browsers", new ObservableCollection<BrowserItem>());
Where the Setting class above saves and gets the ObservableCollection from isolated storage.
MainPage.xaml.cs
private void ShowTab(int index)
{
this.currentIndex = index;
//Settings.Browsers.Value.ElementAt(currentIndex); //ArgumentOutOfRange exception
int count = Settings.Browsers.Value.Count;
if (count <= 0)
{
FullWebBrowser browser = new FullWebBrowser();
browser.InitialUri = "http://www.bing.com";
BrowserItem Browser = new BrowserItem();
Browser.browser = browser;
Browser.url = browser.InitialUri;
Settings.Browsers.Value.Add(Browser);
BrowserHost.Children.Add(Browser.browser);
}
//SearchBar.Text = Settings.Browsers.Value.ElementAt(currentIndex).url ?? "";
if (Settings.Browsers.Value.ElementAt(currentIndex) == null) //ArgumentOutOfRangeException
{
FullWebBrowser browser = new FullWebBrowser();
browser.InitialUri = "http://www.bing.com";
BrowserItem Browser = new BrowserItem();
Browser.browser = browser;
Browser.url = browser.InitialUri;
Settings.Browsers.Value.Add(Browser);
BrowserHost.Children.Add(Browser.browser);
}
for (int i = 0; i < Settings.Browsers.Value.Count; i++)
{
if (Settings.Browsers.Value.ElementAt(i) != null)
{
Settings.Browsers.Value.ElementAt(i).browser.Visibility = i == this.currentIndex ? Visibility.Visible : Visibility.Collapsed;
}
}
}
The ArgumentOutOfRangeException first occurs on Settings.Browsers.Value.ElementAt(currentIndex); in the ShowTab method, and everywhere else containing the same statement. I would just like to show the webbrowser of the corresponding index value in the ObservableCollection in MainPage.
You need to add items to the collection somehow from somewhere. There should be some code like
OR
You cannot get item from an empty collection and you index must not be greater than
Count-1