Combobox value is not selected by ZipFile compression - c#

I am Creating Windows Application.I am using FolderBrowserDialog textBox1 ComboBox and button. In my button click I want to select a combo box value and store in a zip file. But it is not accepting combo box value and showing me error. Any idea how to resolve?
namespace WinDataStore
{
public partial class Form1 : Form
{
ComboBox comboBox;
public Form1()
{
InitializeComponent();
var daysOfWeek = new[] { "RED", "GREEN", "BLUE"};
// Initialize combo box
comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
string s = (string)comboBox.SelectedItem;
using (ZipFile zip = new ZipFile())
{
zip.AddFile("s", "files");
zip.Save("z.zip");
}
}
}
}

Based on your comment above:
System.IO.FileNotFoundException
The .Add() method that you're using expects a file name:
zip.AddFile("s", "files");
Do you really have a file that's just named "s" in the current working directory? The runtime is telling you that you don't. And I'm inclined to believe it. You can't add a file which doesn't exist.
You do have a string variable called s:
string s = (string)comboBox.SelectedItem;
Maybe you meant to use that?:
zip.AddFile(s, "files");

Related

How to manipulate or edit a txt file from textbox and save the modification to the main file or new file

I've managed to open a txt file to a ComboBox where it shown only the second element"100", and if I select one of the items in ComboBox will show me the the first element witch is "firstName", the problem is I want to modify the first element from the textbox and save it to the main file or new file on the way that I replace the old element with new one from the textbox and save the file as it was at the beginning
TXT FILE
firstName;;;100;;;0;
firstName;;;100;;;1;
firstName;;;100;;;2;
firstName;;;100;;;3;
firstName;;;0100;;;4;
firstName;;;0100;;;5;
firstName;;;0100;;;6;
firstName;;;0100;;;7;
lastName;;;0100;;;0;
lastName;;;0100;;;1;
lastName;;;0100;;;2;
lastName;;;0100;;;3;
lastName;;;0100;;;4;
lastName;;;0100;;;5;
lastName;;;0100;;;6;
lastName;;;0100;;;7;
i want to change the first elements from the textbox and replace it with user input and save the file as in it were,
example:
//output
john;;;100;;;0;
Patrick;;;100;;;1;
firstName;;;100;;;2;
namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
public string[] lines;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt file (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//string[] lines = File.ReadAllLines(openFileDialog.FileName);
lines = File.ReadAllLines(openFileDialog.FileName);
List<string> result = new List<string>();
string[] par = new string[1];
par[0] = ";;;";
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].Split(par, StringSplitOptions.None);
if (row.Length > 2)
{
if (!result.Contains(row[1]))
result.Add(row[1]);
}
}
foreach (string line in result)
{
comboBox1.Items.Add(line);
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var d = lines;
var t = d.Where(g => g.Contains(comboBox1.Text));
string allItems = "";
foreach (string item in t)
{
string[] r = item.Split(new string[] { ";;;" }, StringSplitOptions.None);
allItems += r[0] + Environment.NewLine;
}
textBox1.Text = allItems;
}
}
}
I've read your code carefully and my understanding may not be perfect but it should be close enough that I can help. One way to achieve your objectives is with data binding and I'll demonstrate this step by step.
"open a txt file to a combobox"
In your main form, you'll move the OpenFileDialog so that it is now a member variable:
private OpenFileDialog openFileDialog = new OpenFileDialog
{
InitialDirectory = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Files"),
FileName = "Data.txt",
Filter = "txt file (*.txt)|*.txt|All files (*.*)|*.*",
FilterIndex = 2,
RestoreDirectory = true,
};
In the main form CTor
Handle event buttonLoad.Click to display the dialog
Handle event openFileDialog.FileOk to read the file.
The DataSource of comboBox will be set to the list of lines read from the file.
Initialize
public MainForm()
{
InitializeComponent();
buttonLoad.Click += onClickLoad;
openFileDialog.FileOk += onFileOK;
comboBox.DataSource = lines;
.
.
.
Disposed += (sender, e) => openFileDialog.Dispose();
}
BindingList<Line> lines = new BindingList<Line>();
private void onClickLoad(object? sender, EventArgs e) =>
openFileDialog.ShowDialog();
In a minute, we'll look at those three things step by step. But first...
Serialize and Deserialize
You have a lot of loose code doing string splits to decode your serializer format. Try consolidating this in a class that is also suitable to be used in a BindingList<Line>. This will be the data source of your combo box. Also consider using a standard serialization format like JSON instead!
class Line : INotifyPropertyChanged
{
// Make a Line from serialized like firstName;;;100;;;0;
public Line(string serialized)
{
// Convert to a stored array
_deserialized = serialized.Split(new string[] { ";;;" }, StringSplitOptions.None);
}
// Convert back to the format used in your file.
public string Serialized => string.Join(";;;", _deserialized);
private string[] _deserialized { get; } // Backing store.
// Convert a list of Lines to a collection of strings (e.g. for Save).
public static IEnumerable<string> ToAllLines(IEnumerable<Line> lines) =>
lines.Select(_ => _.Serialized);
// Determine how a Line will be displayed in the combo box (e.g. "0100").
public override string ToString() => _deserialized[1].ToString();
// Use array syntax to access elements of the split array.
public string this[int index]
{
get => _deserialized[index];
set
{
if(!Equals(_deserialized[index],value))
{
// Send event when any array value changes.
_deserialized[index] = value;
OnPropertyChanged($"{index}");
}
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Load
Once the data file is selected, the raw text file will be shown and the combo box will be populated.
private void onFileOK(object? sender, CancelEventArgs e)
{
lines.Clear();
foreach (var serialized in File.ReadAllLines(openFileDialog.FileName))
{
lines.Add(new Line(serialized));
}
textBoxMultiline.Lines = lines.Select(_=>_.Serialized).ToArray();
comboBox.SelectedIndex = -1;
}
Replacement
Going back to the main form CTor there are three more events we care about:
public MainForm()
{
.
.
.
comboBox.SelectedIndexChanged += onComboBoxSelectedIndexChanged;
textBoxEditor.TextChanged += onEditorTextChanged;
lines.ListChanged += onListChanged;
.
.
.
}
When a new item is selected in the combo box, put it in the text editor.
private void onComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
var item = (Line)comboBox.SelectedItem;
if (item != null)
{
textBoxEditor.Text = item[0];
}
}
When the textEditor text changes, modify the item.
private void onEditorTextChanged(object? sender, EventArgs e)
{
var item = (Line)comboBox.SelectedItem;
if (item != null)
{
item[0] = textBoxEditor.Text;
}
}
When the item changes, update the file display in the big textbox.
private void onListChanged(object? sender, ListChangedEventArgs e)
{
switch (e.ListChangedType)
{
case ListChangedType.ItemChanged:
textBoxMultiline.Lines = lines.Select(_=>_.Serialized).ToArray();
break;
}
}
Save
SaveFileDialog saveFileDialog = new SaveFileDialog
{
InitialDirectory = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Files"),
FileName = "Data.txt",
Filter = "txt file (*.txt)|*.txt|All files (*.*)|*.*",
FilterIndex = 2,
RestoreDirectory = true,
};
private void onClickSave(object? sender, EventArgs e) =>
saveFileDialog.ShowDialog(this);
private void onSaveFileOK(object? sender, CancelEventArgs e)
{
File.WriteAllLines(saveFileDialog.FileName, Line.ToAllLines(lines));
}
I hope this is "close enough" to what you have described that if will give you some ideas to experiment with.

How do I get text from the textbox into Button event in c#

I have created this code
created form in .dll file
and added controles
TextBox dbname = new TextBox();
dbname.BorderStyle = BorderStyle.Fixed3D;
dbname.Location = new Point(236, 81);
Button Create = new Button();
Create.FlatStyle = FlatStyle.Flat;
Create.FlatAppearance.BorderSize = 0;
Create.Location = new Point(261, 115);
Create.Text = "Create";
Create.Click += new System.EventHandler(this.Create_Click);
How do I get text from the text box?
private void Create_Click(object sender , EventArgs e)
{
SaveFileDialog _sfd_ = new SaveFileDialog();
_sfd_.Filter = "Housam Printing |*.HP";
_sfd_.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
_sfd_.FileName = dbname.text;
_sfd_.Title = "Database location";
}
In order to make your controls accessible to the rest of your class, you need to define them at the class level. Then you can initialize them in the constructor or the Form_Load event (or wherever you want), and can access them from other class methods:
public partial class Form1 : Form
{
// Declare your controls at the class level so all methods can access them
private TextBox dbName;
private Button create;
private void Form1_Load(object sender, EventArgs e)
{
dbName = new TextBox
{
BorderStyle = BorderStyle.Fixed3D,
Location = new Point(236, 81)
};
Controls.Add(dbName);
create = new Button
{
FlatStyle = FlatStyle.Flat,
Location = new Point(261, 115),
Text = "Create",
};
create.FlatAppearance.BorderSize = 0;
create.Click += create_Click;
Controls.Add(create);
}
private void create_Click(object sender , EventArgs e)
{
var sfd = new SaveFileDialog
{
Filter = "Housam Printing |*.HP",
InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
FileName = dbName.Text,
Title = "Database location"
};
}
}

compress Data from listbox using ZipFile

I am creating button click event, on clicking it will select data of textbox1 and comboBox1. Further it will search for specific file type from the folder name I provide into textbox1. Currently I am using listbox1 as container for storing value from combobox and textbox. Now I want to Zip the file I got from listbox1. I am using ZipFile to compress it.Now I am stuck in how to call all data from listbox1 for compressing.
namespace WinDataStore
{
public partial class Form1 : Form
{
ComboBox comboBox;
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml",".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*",SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
var comboBox = this.Controls["comboBox"] as ComboBox;
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}

Directory search is Not working after using getfiles

I am using Windows form on which I am using a textbox,folderbrowserdialog and listbox control and two button controls.The task is to retrieve specific file type say .txt from the folder in the textbox1. After getting specific file type from textbox1 I want to display it on listbox1.So I used directory.getfile option but it is showing me error of An unhandled exception of type 'System.IO.DirectoryNotFoundException' .Can any one tell me what is wrong on my code.
namespace WinDataStore
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
var t = this.Controls["textBox1"] as TextBox;
string[] extensions = { ".txt", ".aspx", ".css", ".cs" };
string[] dizin = Directory.GetFiles("t", "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
string[] p = dizin;
listBox1.Items.Add(p);
}
}
}
You must pass path of the folder in first parameter:
Directory.GetFiles(t.Text, "*.*")
instead of just passing "t".
Even you don't need to refer to t while you have textBox1 in the same scope, you can directly use:
Directory.GetFiles(textBox1.Text, "*.*")
Now add array to listbox1:
listBox1.Items.AddRange(dizin);
You can change you code like
Check the value of text is not empty.
you can use addrange() method to add value to listbox(before it was adding array object to list box)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
//var t = this.Controls["textBox1"] as TextBox;
string[] extensions = { ".txt", ".aspx", ".css", ".cs" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
//string[] p = dizin;
//listBox1.Items.Add(p);
}
}
Change your code in this way:
string[] dizin = Directory.GetFiles(t.Text, "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
Becuase you put "t" that is an error, because t is not a string but a variable containing the folder, as I understood looking your code.
The way your are trying to read the path from textbox is not correct. Also do below changes to your code. Also I think there is an issue in the way you're adding items to the listBox. I haven't tested this code. Please try and let me know if you have any issues.
private void button2_Click(object sender, EventArgs e)
{
string path = textBox1.Text;
string[] extensions = { ".txt", ".aspx", ".css", ".cs" };
string[] allFiles = Directory.GetFiles(path);
var validFiles = (from file in allFiles from extension in extensions where file.ToLower().Contains(extension) select file).ToList();
foreach (var validFile in validFiles)
{
listBox1.Items.Add(new ListBoxItem(validFile, validFile));
}
}

How to make each listbox item have its own value via other controls such as numericUpDown and checkbox?

I am trying to create a program where a listbox has a number of items. Each new item has to be automatically intertwined with a checkbox and a numericUpDown. So for example Item A would have the checkbox ticked, with 50 in the numericUpDown while Item B will have the checkbox unchecked and with 25 in the numericUpDown If possible, I would like to do this via dictionary<> This is the code I have so far:
The class I have created
class MediaClass
{
public bool Checked { get; set; }
public int Number { get; set; }
}
This is my dictionary code
public void Dictionary()
{
var dictionary = new Dictionary<String, MediaClass>();
listBox_Movielist.DataSource = new BindingSource(dictionary, null);
}
I would also like this to be saved to a text file. My save code is
private void button_Save_Click(object sender, EventArgs e)
{
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "Text files|*.txt";
savefile.Title = "Save As";
savefile.ShowDialog();
}
My load code is
OpenFileDialog loadfile = new OpenFileDialog();
loadfile.DefaultExt = "txt";
loadfile.Filter = "Text files|*.txt";
loadfile.FilterIndex = 1;
loadfile.CheckFileExists = true;
loadfile.CheckPathExists = true;
loadfile.Multiselect = false;
loadfile.ShowDialog();
System.IO.StreamReader lText = new
System.IO.StreamReader(loadfile.FileName);
listBox_Movielist.Text = lText.ReadToEnd();
Asuming your ListBox is called listbox, add this in the constructor for your window:
listbox.SelectionChanged += (sender, e) =>
{
var item = listbox.SelectedItem as ListBoxItem;
string media = item.Content as string;
if (media != null)
{
//set checkbox to dictionary[media].Checked
//set updown to dictionary[media].Number
}
};
I'm not quite sure why you declare your dictionary in an extra method. This will make it impossible to reference outside of that method. What you probably want is to have the dictionary be a private field. Something like
private Dictionary<String, MediaClass> dictionary = new Dictionary<String, MediaClass>();
somewhere in your window class.

Categories

Resources