I have build this C# for LOADING and SAVING items and subitems from a ListView:
private void Form1_Load(object sender, EventArgs e) {
this.Location=Properties.Settings.Default.FormLocation;
if (Properties.Settings.Default.AllePcer == null) {
Properties.Settings.Default.AllePcer = new StringCollection();
}
var items = new ListViewItem[Properties.Settings.Default.AllePcer.Count];
for (int i = 0; i < items.Length; i++) {
items[i] = new ListViewItem(Properties.Settings.Default.AllePcer[i].Split('|'));
}
this.listView1.Items.AddRange(items);
this.Show();
butten_Help.Focus();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
Properties.Settings.Default.FormLocation=this.Location;
Properties.Settings.Default.AllePcer = new StringCollection();
var items = new List<string>();
foreach (ListViewItem item in this.listView1.Items) {
List<string> subitems = new List<string>();
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems) {
subitems.Add(subitem.Text);
}
items.Add(string.Join("|", subitems)); <<<<<<<<<<<<<<<<<<<<
}
Properties.Settings.Default.AllePcer.AddRange(items.ToArray());
Properties.Settings.Default.Save();
}
The line with the "<<<<<<<<<<<<<<<<<<" gives me compilingerror:
cannot convert from 'System.Collections.Generic.List' to
'string[]'
How can I correct this ?
Related
I'm able to save the textbox text and the listview items to a txt file properly by using:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
//writer.WriteLine(accountText.Text);
writer.WriteLine(accountText.Text);
if (transactionList.Items.Count > 0)
{
foreach (ListViewItem item in transactionList.Items)
{
StringBuilder newString = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
newString.Append(string.Format("{0}\t", listSub.Text));
}
writer.WriteLine(newString.ToString());
}
writer.WriteLine();
}
}
}
}
However, I'm only able to load the textbox and can't seem to get the listview to populate. Here's what I have for that so far:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
accountText.Text = reader.ReadLine();
if (transactionList.Items.Count == 0)
{
foreach (ListViewItem item in transactionList.Items)
{
StringBuilder myString = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
myString.Append(string.Format("{0}\t", listSub.Text));
}
reader.Read();
}
reader.ReadToEnd();
}
}
}
}
Any tips would be appreciated.
You just need to split string by '\t' character, it will return string[]. Then just add these array items to listview.
string[] items = reader.ReadLine().Split('\t');
foreach (var item in items)
{
var listViewItem = new ListViewItem(item);
transactionList.Items.Add(listViewItem);
}
As far as I can tell you're not putting the string into the ListView.
You will want to to do something like this:
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
myString.Append(string.Format("{0}\t", listSub.Text));
listSub.Text = myString.ToString();
}
You need to reverse all your actions while reading
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
accountText.Text = reader.ReadLine();
while(!reader.EndOfStream)
{
var myString = reader.ReadLine();
var subitems = myString.Split("\t");
// Create ListItem and assign subItems here...
transactionList.Items.Add(new ListviewItem(subitems));
}
}
}
}
}
I am trying to list all combobox items in one messagebox. but all i get is every item comes up in its own messagebox. I know the messagebox needs to be outside the loop but when i do that it says the variable is unassigned. Any help would be great.
private void displayYachtTypesToolStripMenuItem_Click(object sender, EventArgs e)
{
string yachtTypesString;
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=typeComboBox.Items[indexInteger].ToString();
MessageBox.Show(yachtTypesString);
}
}
Do it like this,
StringBuilder yachtTypesString = new StringBuilder();
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString.AppendLine(typeComboBox.Items[indexInteger].ToString());
}
MessageBox.Show(yachtTypesString.ToString());
NOTE: Do not do string concatenation with a string, use StringBuilder object as doing it in a string creates a new instance.
You can try using Linq:
MessageBox.Show(String.Join(Environment.NewLine, typeComboBox.Items.Cast<String>()));
and let it do all the work for you
Try this
string yachtTypesString="";
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=yachtTypesString + typeComboBox.Items[indexInteger].ToString();
}
MessageBox.Show(yachtTypesString);
list all combobox items in one messagebox
Please play with Below code To Get Combobox all Text
private void Form1_Load(object sender, EventArgs e)
{
DataTable dtcheck = new DataTable();
dtcheck.Columns.Add("ID");
dtcheck.Columns.Add("Name");
for (int i = 0; i <= 15; i++)
{
dtcheck.Rows.Add(i, "A" + i);
}
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = dtcheck;
}
}
private void button1_Click(object sender, EventArgs e)
{
string MessageText = string.Empty;
foreach(object item in comboBox1.Items)
{
DataRowView row = item as DataRowView;
MessageText += row["Name"].ToString() + "\n";
}
MessageBox.Show(MessageText, "ListItems", MessageBoxButtons.OK,MessageBoxIcon.Information);
}
First, I have filled a list object with the data from xml file. After that, I have filled a ListView with the necessary fields, without any problem. How can I get the index from the selected ListView item and then give appropriate value to some textbox?
This is the code for it:
private void Form1_Load(object sender, EventArgs e)
{
List<Tasks> taskList = new List<Tasks>();
listView1.Columns.Add("Date:");
listView1.Columns.Add("Job:");
listView1.Columns.Add("Client Name");
listView1.Columns.Add("Submitted by");
taskList = getTasks();
listView1.Items.Clear();
for (int i = 0; i < taskList.Count; i++)
{
Tasks task = taskList.ElementAt(i);
ListViewItem row = new ListViewItem();
row.Text=task.date.ToString();
row.SubItems.Add(task.job);
row.SubItems.Add(task.clientName);
row.SubItems.Add(task.submittedBy);
listView1.Items.Add(row);
}
}
public List<Tasks> getTasks()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("data.xml");
XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/tasks/task");
List<Tasks> taskList = new List<Tasks>();
foreach (XmlNode node in nodes)
{
Tasks task = new Tasks();
task.id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
task.date = Convert.ToDateTime(node.SelectSingleNode("submittedDate").InnerText);
task.submittedBy = node.SelectSingleNode("submittedBy").InnerText;
task.clientName = node.SelectSingleNode("clientName").InnerText;
task.job = node.SelectSingleNode("job").InnerText;
task.taskCategory = node.SelectSingleNode("taskCategory").InnerText;
task.taskDescription = node.SelectSingleNode("taskDescription").InnerText;
task.hours = node.SelectSingleNode("hours").InnerText;
task.status = node.SelectSingleNode("status").InnerText;
task.isBilled = node.SelectSingleNode("isBilled").InnerText;
task.cost = node.SelectSingleNode("cost").InnerText;
task.followUpInfo = node.SelectSingleNode("followUpInfo").InnerText;
task.invoiceNumber = node.SelectSingleNode("quickBooksInvoiceNo").InnerText;
taskList.Add(task);
}
return taskList;
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
What I need is now how when I click an item from the listView1 to show some value in a textbox? But that value should be taken from the list object taskList, not from the xml document itself.
Store your task ID inside of your item's Tag property:
row.Tag = task.id;
Then handle ListView.SelectedIndexChanged event
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
var id = (int) listView1.SelectedItems[0].Tag;
var currenTask = taskList.Where(t => t.id == id).First();
textBox1.Text = currenTask.taskDescription; // for example
}
}
Also you should define your taskList in the class level, outside of your Form_Load method.Otherwise you can't access it from SelectedIndexChanged event.
List<Tasks> taskList = new List<Tasks>();
private void Form1_Load(object sender, EventArgs e)
{
...
}
I'm trying to remove the selected Item file from the list-view and also from the directory but I couldn't succeed. How can i remove this.?
string destination_dir = System.IO.Directory.GetCurrentDirectory() + #"./4x6";
public ImggLList()
{
InitializeComponent();
ListViewImage.Items.Clear();
DataContextChanged += OnDataContextChanged;
ImageFileCollectionViewModel ImagesViewModel = new ImageFileCollectionViewModel();
ImageFileControler.CompleteViewList(ImagesViewModel, destination_dir);
ListViewImage.DataContext = ImagesViewModel;
}
OnDataContextChanged
private ImageFileCollectionViewModel _currentDataContext = null;
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_currentDataContext == DataContext) return;
if (_currentDataContext != null)
_currentDataContext.SelectedImageFileViewModels = null;
_currentDataContext = DataContext as ImageFileCollectionViewModel;
if (_currentDataContext != null)
_currentDataContext.SelectedImageFileViewModels = ListViewImage.SelectedItems;
}
Button Function:
private List<ImageFileViewModel> copyOfSelection;
private ImageFileCollectionViewModel imageFileCollection;
private void Delte_Photo_Click(object sender, RoutedEventArgs e)
{
copyOfSelection = imageFileCollection.SelectedImageFileViewModels.Cast<ImageFileViewModel>().ToList();
foreach (ImageFileViewModel ifvm in copyOfSelection)
{
copyOfSelection.Remove(ifvm);
File.Delete(destination_dir);
}
}
NullExeception Error:
for (int i = 0; i < copyOfSelection.Count; i++)
{
copyOfSelection.RemoveAt(i);
File.Delete(destination_dir);
}
Iam new in programming.In windows Form application ,I want user can write a url in textbox and add (with button) in listbox as a favorite list,then user can click in listbox and then go to browser, finaly can save and open the list? whitout Microsoft Sql Database.I Need a source code.
textbox: (Enter your WebSite) : www.google.com
Button:ADD To List Box
Listbox:WWW.Google.com
Button :Save
Button :Open
You have to save the ListBox.Items as plain text file if not wanting to use database. Without binding, this simple problem becomes a little nasty if you start digging into writing it. Here is one of the solution you may need:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int lastIndex = -1;
bool suppressSelectedIndexChanged;
//Click event handler for buttonAdd
private void buttonAdd_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
suppressSelectedIndexChanged = true;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
suppressSelectedIndexChanged = false;
}
//Click event handler for buttonRemove
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndices.Count == 0) return;
int k = listBox1.SelectedIndices[0];
suppressSelectedIndexChanged = true;
for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
suppressSelectedIndexChanged = false;
lastIndex = -1;
listBox1.SelectedIndex = k < listBox1.Items.Count ? k : listBox1.Items.Count - 1;
if (listBox1.Items.Count == 0) textBox1.Clear();
}
//Click event handler for buttonSave
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "URLs file|*.urls";
save.FileOk += (s, ev) =>
{
using (StreamWriter writer = File.CreateText(save.FileName))
{
foreach (object item in listBox1.Items)
{
writer.WriteLine(item.ToString());
}
}
};
save.ShowDialog();
}
//Click event handler for buttonOpen
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "URLs file|*.urls";
open.FileOk += (s, ev) =>
{
listBox1.Items.Clear();
using (StreamReader reader = File.OpenText(open.FileName))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
};
open.ShowDialog();
}
//SelectedIndexChanged event handler for listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (suppressSelectedIndexChanged) return;
if (lastIndex > -1)
{
listBox1.Items[lastIndex] = textBox1.Text;
}
lastIndex = listBox1.SelectedIndex;
if (listBox1.SelectedIndex > -1)
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
}
//Click event handler for buttonVisit
private void buttonVisit_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem == null) return;
System.Diagnostics.Process.Start(listBox1.SelectedItem.ToString());
}
}
Here is the GUI screen shot for you to know which controls are needed:
private void btnAdd_Click(object sender, EventArgs e)
{
string _webstring = #"http://";
string _website = _webstring + textBox1.Text;
listBox1.Items.Add(_website);
using (StreamWriter w = File.AppendText("websites.txt"))
{
WriteLog(_website, w);
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
private void btnLaunch_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("iexplore.exe", listBox1.SelectedItem.ToString());
}
private void btnSave_Click(object sender, EventArgs e)
{
using (StreamWriter w = File.AppendText("websites.txt"))
{
foreach (string items in listBox1.Items)
{
WriteLog(items, w);
}
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
public static void WriteLog(string logMessage, TextWriter w)
{
w.WriteLine(logMessage, logMessage);
}
public static void DisposeLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
private void btnRetrieve_Click(object sender, EventArgs e)
{
using (TextReader txtRead = File.OpenText("Websites.txt"))
{
string _text = "";
string[] _textArray = null;
while ((_text = txtRead.ReadLine()) != null)
{
_textArray = _text.Split('\t');
listBox1.Items.Add(txtRead.ReadLine());
}
txtRead.Close();
}
}
hope this helps.. thanks