I am currently using geolocation to get the user's country name. Here is my code:
navigator.geolocation.getCurrentPosition(function (pos) {
var latlng = pos.coords.latitude + "," + pos.coords.longitude;
var apiurl = 'http://maps.google.com/maps/geo?output=json&sensor=false&q=' + latlng;
var yqlqry = encodeURIComponent('select * from json where url="' + apiurl + '"');
var yqlurl = 'http://query.yahooapis.com/v1/public/yql?q=' + yqlqry + '&format=json&callback=?';
$.getJSON(yqlurl, function (data) {
var countryName = data.query.results.json.Placemark.AddressDetails.Country.CountryName;
var newCountryName = countryName.toLowerCase();
if (newCountryName == "united states")
newCountryName = "us";
else if (newCountryName == "england" || newCountryName == "ireland" || newCountryName == "scotland" || newCountryName == "wales" || newCountryName == "northern ireland")
newCountryName = "uk";
else if (newCountryName == "australia")
newCountryName = "au";
else if (newCountryName == "canada")
newCountryName = "ca";
else
newCountryName = "world";
$('a[title = "' + newCountryName + '"]').trigger('click');
});
});
I would rather use something on the server side. Does anyone know if you can get the user's country name in C#?
On the server side, the only thing you can reply upon is the IP address, which you can use to perform a location lookup. There are free databases out there of IP address-to-location mappings, or you can use HostIP.info.
Look at https://stackoverflow.com/questions/372591/how-to-get-city-country-and-country-code-for-a-particular-ip-address-in-asp-ne for more info.
I did this for WP7, but code is almost the same in standard.net framework: http://www.felicepollano.com/2012/01/11/AnImplementationOfICivicAddressResolverForWP7.aspx
the class doing the job is below. Just remove ICivicAddressResolver that is a WP7 dependency and create your own interface.
public class AddressResolver:ICivicAddressResolver
{
string language = "en-GB";
public AddressResolver()
{
}
public AddressResolver(string language)
{
this.language = language;
}
[DataContract]
public class AddressInfo
{
[DataMember(Name = "formatted_address")]
public string FormattedAddress { get; set; }
}
[DataContract]
public class ResultInfo
{
[DataMember(Name = "results")]
public AddressInfo[] Info { get; set; }
}
readonly string URITemplate = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=true&language={2}";
#region ICivicAddressResolver Members
public CivicAddress ResolveAddress(GeoCoordinate coordinate)
{
throw new NotImplementedException("Use async version instead");
}
public void ResolveAddressAsync(GeoCoordinate coordinate)
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
client.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
var ainfo = ReadToObject<ResultInfo>(e.Result);
ResolveAddressCompleted(this, new ResolveAddressCompletedEventArgs(ToCivic(ainfo),e.Error,false,null));
}
else
{
ResolveAddressCompleted(this, new ResolveAddressCompletedEventArgs(new CivicAddress(), e.Error, false, null));
}
};
client.DownloadStringAsync(new Uri(GetFormattedUri(coordinate)));
}
private CivicAddress ToCivic(ResultInfo ainfo)
{
List<string> res = new List<string>();
foreach (var single in ainfo.Info)
{
res.Add(single.FormattedAddress);
}
if (res.Count > 0)
return new CivicAddress() { AddressLine1 = res[0] };
else
return new CivicAddress() { AddressLine1 = "#UNKNOWN#" };
}
public event EventHandler<ResolveAddressCompletedEventArgs> ResolveAddressCompleted = delegate { };
#endregion
private string GetFormattedUri(GeoCoordinate coord)
{
return string.Format(CultureInfo.InvariantCulture, URITemplate, coord.Latitude, coord.Longitude,language);
}
public static T ReadToObject<T>(string json) where T : class
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
T res = ser.ReadObject(ms) as T;
ms.Close();
return res;
}
}
Why don't you try IP2Location's API ?
You could just pass your ipaddress like this.
http://api.ip2location.com/?ip=145.228.219.221&key=demo
More info at
http://www.ip2location.com/ip-country-web-service.aspx
Don't know if this will help but in local this
CultureInfo.CurrentCulture.Name
return something like "en-GB" or "fr-FR" depending of your current locale
Related
public class PageParser
{
public List<Websitedata> PageParserMethod()
{
var websitedata = new List<Websitedata>();
HtmlWeb web = new HtmlWeb();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HtmlDocument doc = web.Load("https://www.sullivanautomotivegroup.net/");
var metaTags = doc.DocumentNode.SelectNodes("//meta");
var foundAppropriateMetaTag = false;
if (metaTags != null)
{
foreach (var tag in metaTags)
{
if (tag.Attributes["name"] != null && tag.Attributes["content"] != null)
{
foundAppropriateMetaTag = true;
var name = tag.Attributes["name"].Value;
var content = tag.Attributes["content"].Value;
//items.Add(new { name, content });
Websitedata info = new Websitedata();
info.name = name;
info.content = content;
websitedata.Add(info);
}
}
}
//var linksOnPage = doc.DocumentNode.Descendants.SelectNodes("//link");
var linksOnPage = from lnks in doc.DocumentNode.Descendants()
where lnks.Name == "a" &&
lnks.Attributes["href"] != null &&
lnks.InnerText.Trim().Length > 0
select new
{
Url = lnks.Attributes["href"].Value,
Text = lnks.InnerText,
};
if (linksOnPage != null)
{
foreach (var tag in linksOnPage)
{
foundAppropriateMetaTag = true;
var rel = tag.Text;
var href = tag.Url;
Websitedata info = new Websitedata();
info.rel = rel;
info.href = href;
websitedata.Add(info);
//items.Add(new { rel, href });
}
}
var scriptGoogleTagManager = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("www.googletagmanager.com"));
if (scriptGoogleTagManager != null)
{
foreach (var tag in scriptGoogleTagManager)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.GoogleTag = abc;
websitedata.Add(info);
}
}
}
var FacebookPixel = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("connect.facebook.net"));
if (FacebookPixel != null)
{
foreach (var tag in FacebookPixel)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.FacebookPixel = abc;
websitedata.Add(info);
}
}
}
var newrelic = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("newrelic"));
if (newrelic != null)
{
foreach (var tag in newrelic)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.NewRelic = abc;
websitedata.Add(info);
}
}
}
var adobelinks = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("adobe"));
if (adobelinks != null)
{
foreach (var tag in adobelinks)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.NewRelic = abc;
websitedata.Add(info);
}
}
}
//www.google-analytics.com
var googleAnalytics = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("www.google-analytics.com/analytics.js"));
if (googleAnalytics != null)
{
foreach (var tag in googleAnalytics)
{
{
foundAppropriateMetaTag = true;
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.FacebookPixel = abc;
websitedata.Add(info);
}
}
}
return websitedata;
}
}
public class Websitedata
{
public string name { get; set; }
public string content { get; set; }
public string rel { get; set; }
public string href { get; set; }
public string GoogleTag { get; set; }
public string FacebookPixel { get; set; }
public string NewRelic { get; set; }
}
Hi, I have used Html agility pack to parse contents of a website but have no idea how to parse retrieved contents of scripts and serialize the same to retrieve useful information. I want to store all the contents received from website to a class.I am stuck in the problem and unable to find any solution. kindly help me!!!
I have a below class. I will get two objects List<Client> data1 and List<Client> data2. I want to compare data1 and data2 with each of the attribute value.
For example, if data1 object has the LastName=a and ClientId=1,..etc and if data2 list has the same set of data i want to push that into one more list.
Any idea, how can we achieve this using LINQ/Minimal code?
public class Client
{
public int ClientId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
using Intersect
List<Client> data1 = new List<Client>();
List<Client> data2 = new List<Client>();
List<Client> newlst = new List<Client>();
Client obj = new Client();
obj.ClientId = 1;
obj.LastName = "a";
obj.FirstName = "n";
obj.Email = "e";
data1.Add(obj);
data2.Add(obj);
obj = new Client();
obj.ClientId = 2;
obj.LastName = "a";
obj.FirstName = "f";
obj.Email = "e";
data1.Add(obj);
newlst = data1.Intersect(data2).ToList();
I have used IEqualityComparer which is used to compare both the collection and Intersect will give the common value.I have tested the code for few scenario. You can check for all the scenario.
Hope this code will be helpful.
namespace UnitTestProject
{
[TestClass]
public class CompareTwoGenericList
{
[TestMethod]
public void TestMethod1()
{
var coll = GetCollectionOne();
var col2 = GetCollectionTwo();
//Gives the equal value
var commonValue = coll.Intersect(col2, new DemoComparer()).ToList();
//Difference
var except=coll.Except(col2, new DemoComparer()).ToList();
}
public List<Demo> GetCollectionOne()
{
List<Demo> demoTest = new List<Demo>()
{
new Demo
{
id=1,
color="blue",
},
new Demo
{
id=2,
color="green",
},
new Demo
{
id=3,
color="red",
},
};
return demoTest;
}
public List<Demo> GetCollectionTwo()
{
List<Demo> demoTest = new List<Demo>()
{
new Demo
{
id=1,
color="blue",
},
new Demo
{
id=2,
color="green",
},
new Demo
{
id=4,
color="red",
},
};
return demoTest;
}
}
// Custom comparer for the Demo class
public class DemoComparer : IEqualityComparer<Demo>
{
// Products are equal if their color and id are equal.
public bool Equals(Demo x, Demo y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the demo properties are equal.
return x.color == y.color && x.id == y.id;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Demo demo)
{
//Check whether the object is null
if (Object.ReferenceEquals(demo, null)) return 0;
//Get hash code for the color field if it is not null.
int hashColor = demo.color == null ? 0 : demo.color.GetHashCode();
//Get hash code for the id field.
int hashId = demo.id.GetHashCode();
//Calculate the hash code for the product.
return hashColor ^ hashId;
}
}
}
Create Your new class ClientView
public class ClientView{
public int ClientId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
List lst = new List();
var data = from n in db.client
select new ClientView()
{
ClientId = n.ClientId ,
LastName = n.LastName ,
FirstName = n.FirstName,
};
var data1 = from n in db.client
select new ClientView()
{
ClientId = n.ClientId ,
LastName = n.LastName ,
FirstName = n.FirstName,
};
lst.AddRange(data);
lst.AddRange(data1);
List<ClientView> lst1 = new List<ClientView>();
foreach (var singlelst in lst)
{
ClientView newClient = new ClientView ();
newClient.Id = singlelst.Id;
newClient.આપેલ = singlelst.LastName;
newClient.આપેલતારીખ = singlelst.FirstName;
lst1.Add(newClient);
}
Try this:
public IEnumerable<PropertyInfo> GetVariance(Client user)
{
foreach (PropertyInfo pi in user.GetType().GetProperties()) {
object valueUser = typeof(Client).GetProperty (pi.Name).GetValue (user);
object valueThis = typeof(Client).GetProperty (pi.Name).GetValue (this);
if (valueUser != null && !valueUser.Equals(valueThis))
yield return pi;
}
}
IEnumerable<PropertyInfo> variances = data1.GetVariance (data2);
foreach (PropertyInfo pi in variances)
Console.WriteLine (pi.Name);
I am implementing a city search so I want a Autofill with the functionality where when I select a city I want the ID to be sent back to the API. to populate some other fields.
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
string text = sender.Text;
if (text.Length >= 3)
{
GetCities(text);
sender.ItemsSource = await Task<string[]>.Run(() => { return this.GetSuggestions(text); });
}
else
{
sender.ItemsSource = new string[] { "No suggestions..." };
}
}
}
My Get response class
private async void GetCities(string city)
{
try
{
string baseAddress = Url.url + "searchCities?q="+city+"&access_token=" + tcm;
HttpClient httpClient = new HttpClient();
string co = "";
var content = await httpClient.GetAsync(new Uri(baseAddress));
if (!content.IsSuccessStatusCode)
{
TokenGenerator tc = new TokenGenerator();
tc.GetToken();
tcm = TokenManager.accessT.access_tocken;
HttpClient client = new HttpClient();
content = await client.GetAsync(new Uri(baseAddress));
}
co = await content.Content.ReadAsStringAsync();
AutofillHelper result = JsonConvert.DeserializeObject<AutofillHelper>(co);
foreach (var item in result.data)
{
suggestions = new string [] {item.city} ;
}
}
catch (Exception ex)
{
dispatcherTimer.Stop();
throw new Exception(ex.ToString());
}
}
private string[] GetSuggestions(string text)
{
string[] result = null;
result = suggestions.Where(x => x.StartsWith(text)).ToArray();
return result;
}
My Get Set
class Autofill
{
public string city_id { get; set; }
public string city { get; set; }
}
class AutofillHelper
{
public List<Autofill> data { get; set; }
}
I want it to display the response from the API for the person to select it. A Run time error is thrown. Can someone please guide me what has gone wrong.
Any kind of help is appreciated...
referring to this link : http://www.objc.io/issue-5/multitasking.html i can now send a silent push notification on ios by setting content-available=1
i'm using moon apns on c# to send the push notification but i can not find this property to send a silent push (i'm using a development certificate)
below is my code :
string p12File = "test.p12";
string p12FilePassword = "1234";
bool sandbox = false;
var push = new PushNotification(sandbox, p12File, p12FilePassword);
NotificationPayload payload1;
payload1 = new NotificationPayload(testDeviceToken, message, 0, "Silence.m4R");
payload1.AddCustom("message", "HIDDEN");
var notificationList = new List<NotificationPayload>() { payload1 };
var rejected = push.SendToApple(notificationList);
foreach (var item in rejected)
{
return false;
}
any idea how can send this using moon apns :
{
"aps" : {
"content-available" : 1
},
"content-id" : 42
}
System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace MoonAPNS
{
public class NotificationPayload
{
public NotificationAlert Alert { get; set; }
public string DeviceToken { get; set; }
public int? Badge { get; set; }
public string Sound { get; set; }
internal int PayloadId { get; set; }
public int Content_available { get; set; }
public Dictionary<string, object[]> CustomItems
{
get;
private set;
}
public NotificationPayload(string deviceToken)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert();
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge, string sound)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge, string sound,int content_available)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
Content_available = content_available;
CustomItems = new Dictionary();
}
public void AddCustom(string key, params object[] values)
{
if (values != null)
this.CustomItems.Add(key, values);
}
public string ToJson()
{
JObject json = new JObject();
JObject aps = new JObject();
if (!this.Alert.IsEmpty)
{
if (!string.IsNullOrEmpty(this.Alert.Body)
&& string.IsNullOrEmpty(this.Alert.LocalizedKey)
&& string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
&& (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0))
{
aps["alert"] = new JValue(this.Alert.Body);
}
else
{
JObject jsonAlert = new JObject();
if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);
if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());
if (!string.IsNullOrEmpty(this.Alert.Body))
jsonAlert["body"] = new JValue(this.Alert.Body);
if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);
aps["alert"] = jsonAlert;
}
}
if (this.Badge.HasValue)
aps["badge"] = new JValue(this.Badge.Value);
if (!string.IsNullOrEmpty(this.Sound))
aps["sound"] = new JValue(this.Sound);
if (this.Content_available == 1)
aps["content-available"] = new JValue(this.Content_available);
json["aps"] = aps;
foreach (string key in this.CustomItems.Keys)
{
if (this.CustomItems[key].Length == 1)
json[key] = new JValue(this.CustomItems[key][0]);
else if (this.CustomItems[key].Length > 1)
json[key] = new JArray(this.CustomItems[key]);
}
string rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);
StringBuilder encodedString = new StringBuilder();
foreach (char c in rawString)
{
if ((int)c < 32 || (int)c > 127)
encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
else
encodedString.Append(c);
}
return rawString;// encodedString.ToString();
}
public override string ToString()
{
return ToJson();
}
}
I have spent hours trying to figure out why my database cannot find the table I have found numerous examples and none have seemed to help. I have created a separate class to handle the database operations so I can use it on multiple pages.
Here is the code
[Table]
public class MatchItem
{
[Column(IsPrimaryKey = true, CanBeNull=false,IsDbGenerated=true)]
public int MatchID { get; set; }
[Column(CanBeNull = false)]
public string MatchNumber { get; set; }
[Column(CanBeNull = false)]
public string EventName { get; set; }
[Column(CanBeNull = false)]
public DateTime Time { get; set; }
[Column(CanBeNull = false)]
public string[] RedTeams { get; set; }
[Column(CanBeNull = false)]
public string[] BlueTeams { get; set; }
[Column(CanBeNull = false)]
public int RedFinal { get; set; }
[Column(CanBeNull = false)]
public int BlueFinal{ get; set; }
}
Here is the Data context
public class MatchDataContext:DataContext
{
public MatchDataContext(string connectionString) :
base(connectionString)
{
}
public Table<MatchItem> Matches
{
get
{
return this.GetTable<MatchItem>();
}
}
}
I made a class so I could use it on multiple pages
public class MatchDBManager
{
private static string connectionString = #"Data Source=isostore:/DB.sdf";
public MatchDBManager()
{
initialize();
}
public void initialize()
{
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
if (Mchdb.DatabaseExists())
{
Console.WriteLine("DB already exists");
}
else
{
Mchdb.CreateDatabase();
Console.WriteLine("DB created");
}
}
}
public void addMatchData(IList<MatchItem> data)
{
//this.clearData();
//initialize();
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
Mchdb.Matches.InsertAllOnSubmit(data);
Mchdb.SubmitChanges();
}
}
public IList<MatchItem> getTeamData(string teamNum)
{
IList<MatchItem> MatchList = null;
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
IQueryable<MatchItem> mchQuery = from mch in Mchdb.Matches where (mch.RedTeams[0] == teamNum || mch.RedTeams[1] == teamNum || mch.RedTeams[2] == teamNum || mch.BlueTeams[0] == teamNum || mch.BlueTeams[1] == teamNum || mch.BlueTeams[2] == teamNum) select mch;
MatchList = mchQuery.ToList();
}
return MatchList;
}
public IList<MatchItem> getEventData(string eventID)
{
IList<MatchItem> MatchList = null;
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
IQueryable<MatchItem> mchQuery = from mch in Mchdb.Matches where mch.Event == eventID select mch;
MatchList = mchQuery.ToList();
}
return MatchList;
}
private void clearData()
{
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
if (Mchdb.DatabaseExists())
{
Mchdb.DeleteDatabase();
}
}
}
}
I have the error The specified table does not exist[Match].
Added here is where I download
public IList<MatchItem> ParseXML(XmlReader reader)
{
//List<string> save = new List<string>();
List<MatchItem> MatchList= new List<MatchItem>();
XElement matchData;
matchData = XElement.Load(reader);
StringBuilder output = new StringBuilder();
int count = 0;
var matches = from item
in matchData.Elements("match")
select item;
foreach (XElement eachmatch in matches)
{
MatchItem mch = new MatchItem();
string Time = ((eachmatch.Element("pubdate").Value).ToString());
mch.EventName = ((eachmatch.Element("event").Value).ToString());
mch.MatchNumber = ((eachmatch.Element("mch").Value).ToString() + (eachmatch.Element("typ").Value).ToString());
string[] RT = { eachmatch.Element("red1").Value.ToString(), eachmatch.Element("red2").Value.ToString(), eachmatch.Element("red3").Value.ToString() };
string[] BT = { eachmatch.Element("blue1").Value.ToString(), eachmatch.Element("blue2").Value.ToString(), eachmatch.Element("blue3").Value.ToString() };
string RF = ((eachmatch.Element("rfin").Value).ToString());
string BF = ((eachmatch.Element("bfin").Value).ToString());
// Time = Time.Substring(0, (Time.IndexOf("+") - 1));
mch.Time = DateTime.Parse(Time);
mch.RedTeams = RT;
mch.BlueTeams = BT;
mch.RedFinal = int.Parse(RF);
mch.BlueFinal= int.Parse(BF);
mch.MatchID = count;
count += 1;
MatchList.Add(mch);
}
return MatchList;
}
This is where I call this method
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
initializeDB();
if (e.Error == null)
{
XmlReader reader = XmlReader.Create(new StringReader(e.Result));
DownloadInfo di = new DownloadInfo();
IList <MatchItem>data= di.ParseXML(reader);
outputer(data);
addData(data.ToList<MatchItem>());
}
else
{
IList<MatchItem> data = getTeamData(strMyTeam);
outputer(data);
}
}
I ended up removing the DatabaseManager class and putting the functions in the main code
Then I output them to the screen here
public void outputer(IList<MatchItem> mch)
{
for (int i = 0; i < mch.Count; i++)
{
Score sc = new Score();
sc.Width = lsbData.Width;
sc.Height = sc.Height;
sc.Time = mch[i].Time.ToString();
sc.Event = mch[i].EventName;
sc.RT = mch[i].RedTeams[0] + " " + mch[i].RedTeams[1] + " " + mch[i].RedTeams[2];
sc.BT = mch[i].BlueTeams[0] + " " + mch[i].BlueTeams[1] + " " + mch[i].BlueTeams[2];
sc.RF = mch[i].RedFinal.ToString();
sc.BF = mch[i].BlueFinal.ToString();
lsbData.Items.Add(sc);
}
}
*note:score is a custom control that works(and worked) before the database code *
I don't see where you actually create a Match Object.
if you have you need to include that code in the question as well. and if you haven't, that would explain why it doesn't exist.
Addition
in order to add Match Objects to a list you will have to create the objects first then add them to the list, I don't think you can create the whole list of objects before creating each individual object.
more Additional Information
the object still needs to be created before you can add items to it. that is what the error is telling you. you don't have the object to insert data into.
Match Table1 = new Match();
this creates a new Match object which allows you to access the pieces of the object and insert data into the object like this
Table1.MatchNumber = 42
you can't add to something to a memory location until you set aside that memory location for that specific person and give it a name.
when you create that class you can add functions and all sorts of fun stuff to it, but you can't use any of it until you have created a Match Object.
you can't add something to a list that doesn't exist, you have to create the Match Object first, then add it to the list