Get data from an object and put it in a textbox - c#

I have an object which contains 2 pieces of information in objData[0]. The information is System_ID and Network_ID. The data is coming from a query to a database.
I want to get the data out of the object and display it in two separate text boxes, one for system_ID and one for Network_ID. Right now I am putting them into a combo box.
See below my code:
//get network ID and systenm name
private void cmbAddItem_SelectedIndexChanged(object sender, EventArgs e)
{
FASystems fSys = new FASystems(sConn);
object objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
cmbNetworkID.DataSource = objData;
cmbNetworkID.DisplayMember = "Network_ID";
cmbSysName.DataSource = objData;
cmbSysName.DisplayMember = "System_Name";
// txtNetworkID.Text = objData[0].Network_ID;
}

Assuming your C# compiler is 3.0 or up use the var keyword on the api call
var objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
Let's assume you're correct that there is an array now in objData with a type in it that has at least Network_ID as a member...
txtNetworkID.Text = objData[0].Network_ID;
should work then.

Can you post the function declaration for getSystemNetworkIDFriendlyName and show how you are populating the return type?
I recommend creating a new class to store the NetworkID and SystemID
class SystemInfo
{
public string NetworkID { get; set; }
public string SystemId { get; set; }
}
Rewrite the function getSystemNetworkIDFriendlyName to return an instance of SystemInfo. Then populating your textbox becomes:
FASystems fSys = new FASystems(sConn);
SystemInfo inf o= fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
txtNetworkID.Text = info.NetworkID;
Hope this helps,
KenC

Related

Dropdownlist for, selection options text (from database) becomes vertically single letter using C# razor

I'm trying to create a drop down list for from a dataset column in my SQL Server database. I have successfully linked the data. However, in view, the dropdown list data appears to have a vertically text.
Please see the screen captured below:
What causes this? Please help!
I'm just going to post the relevant code to easy to see.
Here is the line of the html code (I put index 0 for savedCompCoList for testing only to only get the first row):
<div>#Html.DropDownListFor(x => x.objBV.objCompCo.SavedCompCoSelected, new SelectList(Model.objBV.objCompCo.SavedCompCoList[0].CompCo_ID_With_date_List), "Select List", new { style = "width: 250px;" }))</div>
Using xmlDocument for connection to database:
public static XmlDocument GetSavedCompCo()
{
XmlDocument xmlTmp = DatabaseLib.RunStoredProcedure(UDV.spGetSavedCompCoListBV, UDV.connStringUserDB);
return xmlTmp;
}
Using Web method:
[WebMethod]
public XmlDocument GetSavedCompCo() { return BDOLibrary_Val_BV.CompsLib.GetSavedCompCo(); }
My model - here is the loop that loop though (this may be the cause):
public class CompCo
{
private readonly BDOWebService.BDOWebService webS = new BDOWebService.BDOWebService(); //EC: web service
//EC: variables
public List<SavedCompCo> SavedCompCoList { get; set; }
public int SavedCompCoSelected { get; set; }
public CompCo()
{
initSavedCompCoList();
Comps = new List<Company>();
}
private void initSavedCompCoList()
{
SavedCompCoList = new List<SavedCompCo>();
XmlDocument xmlTmp = webS.GetSavedCompCo();
XmlNodeList nodeListSavedCompCo_ID_With_Date = xmlTmp.GetElementsByTagName("CompCo_ID_With_Date");
for (int i = 0; i < nodeListSavedCompCo_ID_With_Date.Count; i++)
{
SavedCompCo SavedCompCoTemp = new SavedCompCo();
SavedCompCoTemp.CompCo_ID_With_date_List = nodeListSavedCompCo_ID_With_Date[i].InnerText.Trim();
SavedCompCoList.Add(SavedCompCoTemp);
}
}
}
Please help and thanks in advance!

How to get previous data in Xamarin.Forms

I am working on an application which is going to show updated dollar and euro rates for Turkey. I want to print green and red arrows depending on if rates went up or down since the last time user opened the app. So my question is how can I get previous data and how can I compare them with the current data?
CODE-BEHIND;
namespace Subasi.A.M.D
{
public partial class MainPage : ContentPage
{
float banknoteSellingUSD = 0;
float banknoteBuyingUSD = 0;
public MainPage()
{
InitializeComponent();
if (Device.OS == TargetPlatform.iOS)
Padding = new Thickness(10, 50, 0, 0);
else if (Device.OS == TargetPlatform.Android)
Padding = new Thickness(10, 20, 0, 0);
else if (Device.OS == TargetPlatform.WinPhone)
Padding = new Thickness(30, 20, 0, 0);
}
private void Button_Clicked(object sender, EventArgs e)
{
XmlDocument doc1 = new XmlDocument();
doc1.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
XmlElement root = doc1.DocumentElement;
XmlNodeList nodes = root.SelectNodes("Currency");
foreach (XmlNode node in nodes)
{
var attributeKod = node.Attributes["Kod"].Value;
if (attributeKod.Equals("USD"))
{
var GETbanknoteSellingUSD = node.SelectNodes("BanknoteSelling")[0].InnerText;
var GETbanknoteBuyingUSD = node.SelectNodes("BanknoteBuying")[0].InnerText;
//if (banknoteSellingUSD > float.Parse(GETbanknoteSellingUSD)) isusdup = false;
//else isusdup = true;
banknoteSellingUSD = float.Parse(GETbanknoteSellingUSD);
banknoteBuyingUSD = float.Parse(GETbanknoteBuyingUSD);
labelUSDBuying.Text = banknoteSellingUSD.ToString("0.00");
labelUSDSelling.Text = banknoteBuyingUSD.ToString("0.00");
}
var attributeKod1 = node.Attributes["Kod"].Value;
if (attributeKod1.Equals("EUR"))
{
var GETbanknoteSellingEU = node.SelectNodes("BanknoteSelling")[0].InnerText;
var GETbanknoteBuyingEU = node.SelectNodes("BanknoteBuying")[0].InnerText;
var banknoteSellingEU = float.Parse(GETbanknoteSellingEU);
var banknoteBuyingEU = float.Parse(GETbanknoteBuyingEU);
labelEUSelling.Text = banknoteSellingEU.ToString("0.00");
labelEUBuying.Text = banknoteBuyingEU.ToString("0.00");
}
}
}
}
}
print green and red arrows depending on if rates went up or down since the last time user opened the app
To achieve this, you will have to store the previous value. The easiest way may be to use the properties dictionary (see here). You can store simple properties within that.
You could capsule the behavior in a class
public class ExchangeCourseSource : IExchangeCourseSource
{
public ExchangeCourseSource(XmlDocument sourceDocument)
{
this.sourceDocument = sourceDocument;
}
public ExchangeCourse GetCourse(string currency)
{
// parse from XML (see your code)
}
}
class ExchangeCourse
{
public string Currency { get; set; }
public double ExchangeRate { get; set; }
public double Difference { get; set; }
}
and decorate this with a class that stores and retrieved the courses to and fro the properties dictionary
public class StoredExchangeCourseSourceDecorator : IExchangeCourseSource
{
public ExchangeCourseSource(IExchangeCourceSource source, Application application)
{
this.source = source;
this.application = application;
}
public ExchangeCourse GetCourse(string currency)
{
var exchangeCourse = source.GetCourse(currency);
if(HasStoredCourse())
{
var storedCourse = GetStoredCourse(currency);
exchangeCourse.Difference = exchangeCourse.ExchangeRate - storedCourse;
}
StoreCourse(exchangeCourse);
return exchangeCourse;
}
private bool HasStoredCourse(string currency)
{
return application.Properties.ContainsKey(currency);
}
private double GetStoredCourse(string currency)
{
return (double)application.Properties[currency];
}
private void StoreCourse(ExchangeCourse exchangeCourse)
{
application.Properties[exchangeCourse.Currency] = exchangeCourse.ExchangeRate;
application.SavePropertiesAsync().Wait();
}
}
OK, so to answer the question, You have to store data somewhere, the easiest method will be in ISharedPreferences to save and restore data.
From AndroidDeveloper :
If you don't need to store a lot of data and it doesn't require
structure, you should use SharedPreferences. The SharedPreferences
APIs allow you to read and write persistent key-value pairs of
primitive data types: booleans, floats, ints, longs, and strings.
The key-value pairs are written to XML files that persist across user
sessions, even if your app is killed. You can manually specify a name
for the file or use per-activity files to save your data.
So it's a good place to store some info and retrieve them.
All you have to do is to get an instance from ISharedPreferences and use ISharedPreferencesEditor to insert and retrieve data.
You find it in Android.Content Namespace
To save your data you can apply this code :
ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = preference.Edit();
editor.PutString("key", "Value");
editor.Apply();
In your case, you can PutFloat
So your data which is "Value" is saved with a key named "key" is now saved
then you can retrieve data by :
ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(this);
var a = preference .GetString("key", "null");//"null" is the default value if the value not found. and the key, it to retrieve a specific data as we stored the data with the key named "key"
In your case, use GetFloat
So you get your value stored in a variable a.
All you have to do is : Store your data in the Sharedpreference when a new data changed or OnSleep() method which will be called when the app closed, then in OnCreate() method in your app, call the data saved in the SharedPreference and compare it with the new data.

Trouble Exporting WPF ListView Data to CSV with Filehelpers

Have hit a wall with this so hopefully SO can be of help and I've not overlooked an obvious question previously answered. I'm trying export data from a ListView (actually SQLite data that's populating it via a list) to a new CSV file - no fancy filepicker as yet, just need to save the file locally (it's a Metro 8.1 App but being deployed to Surface 3, not RT). I've created a method based on examples I've found but it doesn't seem to be writing the file (have searched local machine after attempting export but nothing found). It's compiling fine and I'm not hitting any exceptions when debugging, also I'm using Filehelpers 2.0 as I couldn't get the current version to install (VS 2015 Community). 'Candidate' is the class for the datasource (DB/listview).
Class:
using SQLite;
using FileHelpers;
namespace SolutionName.Model
{
[Table("Candidates")]
[DelimitedRecord(",")]
[IgnoreEmptyLines()]
[IgnoreFirst()]
public class Candidate
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string AreasInterest { get; set; }
} // end class Candidate
} // end namespace
Method (called by a button):
private void WriteCSVFile(List<Candidate> dataSource)
{
//filehelper object
FileHelperEngine engine = new FileHelperEngine(typeof(Candidate));
List<Candidate> csv = new List<Candidate>();
//convert any datasource to csv based object
foreach (var item in dataSource)
{
Candidate temp = new Candidate();
temp.Title = item.Title;
temp.FirstName = item.FirstName;
temp.LastName = item.LastName;
temp.Email = item.Email;
temp.Phone = item.Phone;
temp.AreasInterest = item.AreasInterest;
csv.Add(temp);
} // end foreach
//give file a name and header text
engine.HeaderText = "Title,FirstName,LastName,Email,Phone,AreaInterest";
//save file locally
engine.WriteFile("export.csv", csv);
} // end method WriteCSVFile
Any pointers would be appreciated.
Testing: Passed
Version 3.2: No issues
Version 2.2: No issues
Using either version of FileHelpers this works as expected. I threw the following code into a test console and it ran through perfectly so my only suggestion now is that you are either not passing it data, or attempting to write to either a read-only or invalid location.
Do you see any exceptions in the Output tab of Visual Studio?
Have you confirmed you have data going into the dataSource parameter?
Have you confirmed the full path that you are writing the export.csv to?
Do you have the csv file open in Excel?
Note: that having the CSV open in Excel causes a full lock on the CSV file so you must exit Excel or close the file to be able to write to it
Code:
static void TestMain2(string[] args)
{
List<Candidate> source = new List<Candidate>()
{
new Candidate() { Id = 1, Email = "test1#test.com", Title = "Mr", FirstName = "Fred", LastName = "Flintstone", AreasInterest = "Area1", Phone = "+44 1234 123123" },
new Candidate() { Id = 3, Email = "test2#test.com", Title = "Mr", FirstName = "Barney", LastName = "Rubble", AreasInterest = "Area2", Phone = "+44 1234 231231" },
new Candidate() { Id = 2, Email = "test3#test.com", Title = "Mrs", FirstName = "Wilma", LastName = "Flintstone", AreasInterest = "Area3", Phone = "+44 1234 312312" }
};
WriteCSVFile(source);
}
private static void WriteCSVFile(List<Candidate> dataSource)
{
//filehelper object
FileHelperEngine engine = new FileHelperEngine(typeof(Candidate));
List<Candidate> csv = new List<Candidate>();
//convert any datasource to csv based object
foreach (var item in dataSource)
{
Candidate temp = new Candidate();
temp.Title = item.Title;
temp.FirstName = item.FirstName;
temp.LastName = item.LastName;
temp.Email = item.Email;
temp.Phone = item.Phone;
temp.AreasInterest = item.AreasInterest;
csv.Add(temp);
} // end foreach
//give file a name and header text
engine.HeaderText = "Title,FirstName,LastName,Email,Phone,AreaInterest";
//save file locally
engine.WriteFile("export.csv", csv);
} // end method WriteCSVFile
CSV File
Title,FirstName,LastName,Email,Phone,AreaInterest
0,Mr,Fred,Flintstone,test1#test.com,+44 1234 123123,Area1
0,Mr,Barney,Rubble,test2#test.com,+44 1234 231231,Area2
0,Mrs,Wilma,Flintstone,test3#test.com,+44 1234 312312,Area3
Notes:
The ID column wasn't copied over so this was always zero, but that may just have been because of your sample code.
I believe it's recommended to be using the generic FileHelperEngine rather than typeof() parameter on the base class since this initialises various methods/properties to utilise T rather than just a generic object.
You can try downloading the source to FileHelpers and linking your project directly to the library to debug what's going on internally.
You did previously mention that you have a System.*.dll referencing problem, check that you are using the Full Framework and not a Client one as that may cause that issue. I am not sure whether a W8 universal app allows that though.

Display sharepoint people/group field list's value in people editor

i want to display value of sharepoint people/group value in people editor(web part) when the page is loaded. This is the code that i use to get the value displayed in web part
if(SPContext .Current .ListItem .ID >= 1)
using (SPSite site = new SPSite("sitename"))
{
using (SPWeb web = site.OpenWeb())
{
var id = SPContext.Current.ListItem.ID;
SPList lists = web.Lists["DDClist"];
SPListItem item = lists.GetItemById(id);
{
string test = Convert.ToString(item["Project No"]);
tb_pno.Text = test;
string test2 = Convert.ToString(item["Project Title"]);
tb_pname.Text = test2;
string test3 = Convert.ToString(item["DDC No"]);
tb_idcno.Text = test3;
string test4 = Convert.ToString(item["Date In"]);
TextBox3.Text = test4;
}
}
}
is there a way to do the same thing with people editor?
This is all a little tricky; when I've had to do it before, I use the following to get SPUser object out of a field:
SPUser singleUser = new SPFieldUserValue(
item.Web, item["Single User"] as string).User;
SPUser[] multipleUsers = ((SPFieldUserValueCollection)item["MultipleUsers"])
.Cast<SPFieldUserValue>().Select(f => f.User);
I'm not sure why one user is stored as a string, but multiple users are stored as a specific object; it may also not be consistent in this so you might have to debug a bit and see what the type in your field is.
Once you have these SPUsers, you can populate your PeopleEditor control
using the account names as follows (quite long-winded):
ArrayList entityArrayList = new ArrayList();
foreach(SPUser user in multipleUsers) // or just once for a single user
{
PickerEntity entity = new PickerEntity;
entity.Key = user.LoginName;
entity = peMyPeople.ValidateEntity(entity);
entityArrayList.Add(entity);
}
peMyPeople.UpdateEntities(entityArrayList);
This also performs validation of the users of some kind.
If the page this control appears on may be posted-back, you need the following to be done during the postback in order for the values to be correctly roundtripped; I put it in PreRender but it could happen elsewhere in the lifecycle:
protected override void OnPreRender(EventArgs e)
{
if (IsPostBack)
{
var csa = peMyPeople.CommaSeparatedAccounts;
csa = peMyPeople.CommaSeparatedAccounts;
}
}
If you want to check any error messages that the control generates for you (if the user input is incorrect), you need to have done this switchout already:
var csa = usrBankSponsor.CommaSeparatedAccounts;
csa = usrOtherBankParties.CommaSeparatedAccounts;
//ErrorMessage is incorrect if you haven't done the above
if (!String.IsNullOrEmpty(usrBankSponsor.ErrorMessage))
{
...
}
It's really not very nice and there may be a much better way of handling it, but this is the result of my experience so far so hopefully it will save you some time.

How To add another constructor with parameter in linq class(Table)

I am using LINQ to SQL in an ASP.NET project. While inserting the table I need to convert the values to the particular table object and I need to insert.
For that I created a new constructor in that table with parameter so that I can assign my value to that table object , the assign the functionality is working but while inserting (obj.TS_Questions.InsertOnSubmit(mytableobject);) I get null exception.
my code::
default constructor for my table
public TS_Question()
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
}
constructor created by me
public TS_Question(Guid Quest_QuestIDBL, string Quest_NameBL, Nullable<Guid> Quest_OptionTypeIDBL, Guid Quest_AdminIDBL, Guid Ques_LevelIDBL, int Quest_TimeBL, int Quest_MarkBL, string Qest_ExplanationBL, Nullable<bool> Qest_IsMultipleAnswerBL)
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
this._Quest_QuestID = Quest_QuestIDBL;
this._Quest_Name = Quest_NameBL;
if (Quest_OptionTypeIDBL != null)
{
this._Quest_OptionTypeID = Quest_OptionTypeIDBL;
}
this._Quest_AdminID = Quest_AdminIDBL;
this._Ques_LevelID = Ques_LevelIDBL;
this._Quest_Time = Quest_TimeBL;
this._Quest_Mark = Quest_MarkBL;
this._Qest_Explanation = Qest_ExplanationBL;
this._Qest_IsMultipleAnswer = Qest_IsMultipleAnswerBL;
}
Please help me out from this problem
Honestly, I haven't looked too deep, but it looks like that OnCreated is sitting a little far north... You probably want to call it after you're done setting up your variables. Other than that i'd say make sure you're properly initializing everything in the method calling the constructor.
You can call default constructor like this, it works fine for me:
public partial class MyClass
{
public MyClass(string fieldValue1,int fieldValue2)
: this()
{
this.field1= fieldValue1;
this.field2 = fieldValue2;
}
}
If this do the trick, you can read more about using contructors in C# here.

Categories