compress Data from listbox using ZipFile - c#

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);
}
}
}

Related

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"
};
}
}

how to edit datagridview cells using a secondary textbox?

I have form1 with datagridview (2 columns with 1 column id,1 column text).
I also have "edit button". When i click "edit button", the text column will show in textbox at form2.
In form2 I have "select button" to edit path and "save button".
How can I pass the edited text in form2 to column datagridview in form1 by press "save button".
Code Edit button in form1 (dgv_sourcefolder is datagridview1) :
private void DGV_sourcefolder_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (DGV_sourcefolder.Columns[e.ColumnIndex].Name == "Edit")
{
string y = "";
int i;
i = ((DataGridView)sender).SelectedCells[0].RowIndex;
y = ((DataGridView)sender).Rows[i].Cells[1].Value.ToString();
//MessageBox.Show(y.ToString());
DTO.data = y;
Form2 form = new Form2();
form.Show();
Hide();
}
}
Code Select Button in form2 :
private void Btn_select_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if(fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox1.Text = fbd.SelectedPath;
}
}
Your form should be look like this.
public class Form2 : Form
{
private DataGridViewRow dataGridViewRow;
public Form2(DataGridViewRow row)
{
dataGridViewRow = row;
}
private void Btn_select_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox1.Text = fbd.SelectedPath;
}
}
private void Btn_Save_Click(object sender, EventArgs e)
{
this.dataGridViewRow.Cells[1].Value = textBox1.Text;
}
}
it main form
private void DGV_sourcefolder_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (DGV_sourcefolder.Columns[e.ColumnIndex].Name == "Edit")
{
string y = "";
int i;
i = ((DataGridView)sender).SelectedCells[0].RowIndex;
y = ((DataGridView)sender).Rows[i].Cells[1].Value.ToString();
//MessageBox.Show(y.ToString());
DTO.data = y;
var row = ((DataGridView)sender).Rows[i];
Form2 form = new Form2(row);
form.Show();
Hide();
}
}
Not assuming anything about the data in your data grid, you can make use of the DataGridViewCell's ParseFormattedValue method and FormatedValue property to make the text box in form2 behave just as a text box in the data grid would. This will help if you are not using string as the value type in your data grid.
public Form2
{
TextBox _myTextBox;
public Form2()
{ ... }
public DataGridViewCell CurrentCell {get;set;}
protected override void OnLoad()
{
Assert(CurrentCell != null);
_myTextBox = CurrentCell.FormatedValue;
}
public SubmitBtn_clicked(...)
{
try
{
var cellValue = CurrentCell.ParseFormattedValue(_myTextBox.Text,
CurrentCell.Style, (TypeConverter)null, (TypeConverter)null);
CurrentCell.Value = cellValue;
}
catch(FormatException)
{/*user entered value that cant be parsed*/ }
catch(ArgumentException)
{/*_myTextBox.Text was null or cell's FormattedValueType is not string*/}
}
}

Combobox value is not selected by ZipFile compression

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");

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));
}
}

C# Pass file path from file in listbox to dataconext

I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code. Such as a DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}
Refer the below code.
<StackPanel>
<ListBox x:Name="fileList" Height="100" Drop="fileList_Drop" DisplayMemberPath="Name" AllowDrop="True"/>
<Button Content="Browse" Click="Button_Click"/>
<Rectangle/>
</StackPanel>
public partial class MainWindow : Window
{
ObservableCollection<FileInfo> lst = new ObservableCollection<FileInfo>();
public MainWindow()
{
InitializeComponent();
fileList.ItemsSource = lst;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
if ((bool)dlg.ShowDialog())
{
FileInfo fi= new FileInfo(dlg.FileName);
lst.Add(fi);
}
}
private void fileList_Drop(object sender, DragEventArgs e)
{
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
FileInfo fi = new FileInfo(droppedFilePath);
lst.Add(fi);
}
}
}

Categories

Resources