how to save listbox items in a text file - c#

I am using .Net 3.5 - I have a problem trying list box items to a text file. I am using this code:
if (lbselected.Items.Count != 0) {
string Path = Application.StartupPath + "\\ClientSelected_DCX.txt";
StreamWriter writer = new StreamWriter(Path);
int selectedDCXCount = System.Convert.ToInt32(lbselected.Items.Count);
int i = 0;
while (i != selectedDCXCount) {
string selectedDCXText = (string)(lbselected.Items[i]);
writer.WriteLine(selectedDCXText);
i++;
}
writer.Close();
writer.Dispose();
}
MessageBox.Show("Selected list has been saved", "Success", MessageBoxButtons.OK);
An error occurs for this line:
string selectedDCXText = (string)(lbselected.Items[i]);
The error is:
Unable to cast object of type 'SampleData' to type 'System.String'
please help me

Use string selectedDCXText = lbselected.Items[i].ToString();

You should override ToString method in class, which instances you want to write into file. Inside ToString method you should format correct output string:
class SampleData
{
public string Name
{
get;set;
}
public int Id
{
get;set;
}
public override string ToString()
{
return this.Name + this.Id;
}
}
And then use
string selectedDCXText = (string)(lbselected.Items[i].ToString());

Make sure that you have overridden the ToString method in your SampleData class like below:
public class SampleData
{
// This is just a sample property. you should replace it with your own properties.
public string Name { get; set; }
public override string ToString()
{
// concat all the properties you wish to return as the string representation of this object.
return Name;
}
}
Now instead of the following line,
string selectedDCXText = (string)(lbselected.Items[i]);
you should use:
string selectedDCXText = lbselected.Items[i].ToString();
Unless you have ToString method overridden in your class, the ToString method will only output class qualified name E.G. "Sample.SampleData"

Related

Save a custom type in database by using OpenAccess of Telerik

I would like to save in the database a custom type property which is a class.
The property to save is myProperty with the type CustomTypeClass in the below example:
public class Test
{
private CustomTypeClass myProperty;
public CustomTypeClass MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
}
So, the value to save in the database is the result of the ToString override method:
public class CustomType
{
public int Start { get; set; }
public int End { get; set; }
public CustomType(int start, int end)
{
this.Start = start;
this.End = end;
}
public override string ToString()
{
return "[" + this.Start + "," + this.End + "]";
}
}
I would like to perform the following code for saving in the database:
CustomType value = new CustomType(3, 5);
Test test = new Test();
test.myProperty = value;
database.Add(test);
database.SaveChanges();
How can I do this ?
At the moment, I get the following error:
Unsupported field-type 'CustomTypeClass' found for field 'myProperty' of class 'Test'.
Maybe you did not specify the TransientAttribute for this field or the PersistentAttribute is not specified for the referenced class. [class=Test]
I don't think you'll be able to do that since it's not a known attribute within the database. However, What I've done in the past is something like:
//Save logic:
CustomType value = new CustomType(3, 5);
Test test = new Test();
test.myProperty = value.ToString();
database.Add(test);
database.SaveChanges();
And then create a static method on CustomType to convert it from a string back to an object:
var obj = db.Tests.First();
var customType = CustomType.LoadFromString(obj.myProperty);
Where LoadFromString is a static method on the object and converts it from a string back into an object (by parsing the string).

How to Convert var to string?

How to Convert var to string?
In my windowsphone application page, i want to convert this var DemoHeader to a string.
XDocument myData = XDocument.Load("aarti.xml");
var DemoHeader = from query in myData.Descendants("bookinfo")
select new HeaderT
{
Header = (string)query.Element("header")
};
ContentHeaderLine.Text = DemoHeader.ToString();‏ //LINE GIVING WRONG DATA
public class HeaderT
{
string header;
public string Header
{
get { return header; }
set { header = value; }
}
}
How can i convert var DemoHeader to a string?
First, var is not a type by itself, the type will be inferred from the value by the compiler. Your type is actually HeaderT and your query returns an IEnumerable<HeaderT> (so possibly multiple).
Presuming you want the first header:
HeaderT first = DemoHeader.First();
string firstHeader = first.Header();
or you want all returned separated by comma:
string allHeaders = String.Join(",", DemoHeader.Select(dh => dh.Header()));
If you want that ToString returns something meaningful(instead of name of the type), override it:
public class HeaderT
{
private string header;
public string Header
{
get { return header; }
set { header = value; }
}
public override string ToString()
{
return Header;
}
}
Override ToString() in HeaderT class could help. After that, you DemoHeader variable is a list of HeaderT not a single HeaderT.

checking for values in multiple if statement and storing multiple comments based on results

Can someone give me an example of the best way to return multiple comments from an if statement?
protected string CheckFacility(int FacilityId)
{
var cfacility = new List<string>();
BuildingPresenter b = new BuildingPresenter();
FunctionalAreaPresenter f = new FunctionalAreaPresenter();
if (b.GetBuildings(FacilityId) != null)
{
cfacility.Add("There are Functional Areas associated with this facility. ");
}
if (f.GetFunctionalAreas(FacilityId) != null)
{
cfacility.Add("There are Functional Areas associated with this facility. ");
}
var cfacilitystring = string.Join(",", cfacility);
I'm getting these errors.
Error 3 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments
Error 4 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string[]'
var shirtAttributes = new List<string>();
if (shirt.IsBlack)
{
shirtAttributes.Add("black");
}
if (shirt.IsLarge)
{
shirtAttributes.Add("large");
}
if (shirt.IsLongSleeve)
{
shirtAttributes.Add("long sleeve");
}
var shirtAttributesString = string.Join(",", shirtAttributes);
Output is something like: "black, long sleeve" or "black" or "large, long sleeve"
You have many ways to deal with that, you can create a class and override the ToString() method:
public class Shirt{
public Shirt(string color, string size, string sleeve)
{
Color =color;
Size=size;
Sleeve=sleeve;
}
public string Color {get;set;}
public string Size {get;set}
public string Sleeve {get;set}
public override string ToString(){
return string.Format("shirt is color :{0} , size :{1} and shleeve: {2}",Color,Size,Sleeve )
}
}
So when you run your program after initializing your class with values
Shirt myShirt = new Shirt("black","large","long");
if(myShirt.Color=="black"&& myShirt.Size=="large" && myShirt.Sleeve=="long")
{
return myShirt.ToString();
}
else{
return "no match";//or want you want
}
Hope it will help.

Error with the command System.IO.File.WriteAllLines()

Hello i am trying to save an object that i have been created and its returning to me error: "represents as a series of Unicode character" on this line: System.IO.File.WriteAllLines(#"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne);
here is the code:
main class:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Persone somOne = new Persone("bob", 5, 200);
System.IO.Directory.CreateDirectory(#"C:\Users\1\AppData\Roaming\MYDATA");
// the Error line Is HERE \/
System.IO.File.WriteAllLines(#"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne);
}
}
}
persone class:
namespace ConsoleApplication1
{
class Persone
{
private String name;
private int id;
private int age;
public Persone(String name, int id, int age)
{
setName(name);
setId(id);
setAge(age);
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
}
}
do i need to chang the type of "somOne"? and how?
System.IO.File.WriteAllLines expects array of strings (or IEnumerable<string>) as second parameter, so code you have should not even compile. You can add to your Person class something like:
public string[] ToStringArray()
{
//And put it everything you need to store
return new[] {name, id.ToString(), age.ToString()};
}
and call like this:
System.IO.File.WriteAllLines(#"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne.ToStringArray());
You can't just save an object like that. They don't automatically format themselves for save to disk.
You want to look into either Serialization or override the .ToString() method for the class and use File.WriteAllText() instead.
According to MSDN, File.WriteAllLines requires an IEnumerable<string> or a string[] as input (the full signature is File.WriteAllLines(string, IEnumberable<string>) or File.WriteAllLines(string, string[]) where the first string is the path and the second is the set of lines you wish to write.
Passing your Persone object is not the same. At the very least you would need to override .ToString() on your object, better might be to write a new method .WritePersone() or something like that.
With the first, you'd call WriteAllLines like this:
System.IO.File.WriteAllLines(#"C:\Users\1\AppData\Roaming\MYDATA\hi.txt",
new string[] {somOne.ToString()});
I hope I'm getting your question correctly.
By this
// the Error line Is HERE \/
System.IO.File.WriteAllLines(#"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne);
you are saying you're getting an error on the above line?
You should've got a compile time error there. The 2nd parameter of WriteAllLines takes either an array or IEnumerable of strings.
Try adding this to your Persone class
public string[] Dump()
{
string[] tmp = new string[3];
tmp[0] = id.ToString();
tmp[1] = name;
tmp[2] = age.ToString();
return tmp;
}
then write to file using
System.IO.File.WriteAllLines(#"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", someone.Dump());

difficulty inserting a name to an inserted object of a checkedlistbox

I am abit new in C# and i am trying to insert an object to a CheckedListBox,
so this inserted item will have a title inside the checked list (my object contains a string field inside it which I want to be displayed in the CheckedListBox).
for example this is my class:
public class InfoLayer
{
private string LayerName;
private List<GeoInfo> GeoInfos;
public InfoLayer()
{
LayerName = "New Empty Layer";
GeoInfos = new List<GeoInfo>();
}
public InfoLayer(string LayerName)
{
this.LayerName = LayerName;
GeoInfos = new List<GeoInfo>();
}
public InfoLayer(string LayerName,List<GeoInfo> GeoInfosToClone):this(LayerName)
{
foreach (GeoInfo item in GeoInfosToClone)
{
GeoInfos.Add((GeoInfo)((ICloneable)item).Clone());
}
}
public GeoInfo SearchElement(long id)
{
foreach (GeoInfo info in GeoInfos) // foreach loop running on the list
{
if (info.INFOID == id)
return info; // return the item if we found it
}
return null;
}
public GeoInfo SearchElement(string name)
{
foreach (GeoInfo info in GeoInfos)
{
if (info.INFONAME.CompareTo(name)==0)
return info;
}
return null;
}
public override string ToString()
{
string toReturn = "";
for (int i = 0; i < GeoInfos.Count; i++) // for loop running on the list
{
toReturn += String.Format("{0}\n",GeoInfos[i].ToString()); // piping another geoinfo
}
return toReturn;
}
public string LAYERNAME{get{return LayerName;}}
my class also contains a tostring overrider inside her (not what i want to display)
thanks in advance for your help.
Override ToString() in your class, the class that the object is an instance of.
Edit:
You don't want to display the contents of ToString(). You want to display the LayerName, don't you? Perhaps you should display the values with Databinding instead. Then you can set DisplayMember to your new LAYERNAME property.
I believe this is what you are trying to achieve:
checkedListBox1.Items.Add(yourObject.stringField);
((MyObjectType)checkedListBox1.Items(index)).Name = "whatever"
You will have to know the index of the object you want to change.
You'll just have to override the ToString method in your class so that it returns this Name property value.
public overrides string ToString() {
return Name;
}
It will then display its name when added to your CheckedListbox.

Categories