Hello i have got one listview that has txt files names inside one folder in desktop. So as i right data there is delete update and add so when i select one item and right click i want that data name to fill name textbox when its opened so its like basicly if i pick 1.1.2 and select update delete for will open and fixx textbox1 as the selectd datas name
-i tried few things like public statci string but when i use it and run program listview shows empty like there is nothing inside
private void liste_Load(object sender, EventArgs e)
{
#region listview fonksiyonları
listView1.FullRowSelect = true;
listView1.View = View.Details;
listView1.Columns.Add("Versiyon No", 133, HorizontalAlignment.Left);
listView1.Columns.Add("Açıklama", 200, HorizontalAlignment.Left);
listView1.Columns.Add("Tarih", 154, HorizontalAlignment.Left);
#endregion
#region listviewde txt dosyalarını gösterme
string[] dosyalar = System.IO.Directory.GetFiles(masaustu + "\\Versiyonlar");
string k = "";
int deger = 0;
foreach (var item in dosyalar)
{
ListViewItem lili = new ListViewItem();
deger = item.LastIndexOf("\\");
k = item.Remove(0, deger);
k = k.Remove(0, 1);
lili.Text = k;
StreamReader oku = new StreamReader(masaustu + "\\" + "Versiyonlar" + "\\" + k);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[] { ";", "$" }, StringSplitOptions.RemoveEmptyEntries);
lili.SubItems.Add(dizi[0]);
lili.SubItems.Add(dizi[1]);
listView1.Items.Add(lili);
}
}
#endregion
#region txt içindekileri textboxda göstermek
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
liste frm = new liste();
try
{
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(masaustu + "\\" + "Versiyonlar" + "\\" + a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
textBox1.Text = OkunanVeri;
}
oku.Close();
}
catch
{
}
}
this is the listview codes if its going to help you please help me i just started c#and i cant figure out how to do it
i dont know what u looking for , this may help
in list view form:
private void openMenuItem_Click(object sender, EventArgs e)//contentmenu openbtn
{
if (listView1.SelectedIndices.Count > 0)//in listview form//on_click opnbtn
{
string strSlctdtext=Convert.ToString(listView1.Items[listView1.SelectedIndices[0]].SubItems[1].Text);
TextBoxform objTextBoxform = new TextBoxform(strListSelectedtext);
if (objTextBoxform.ShowDialog() == DialogResult.OK)
{
//do somthing if u want some output from textboxform in return
}
}
}
in textbox form
public TextBoxform(string strListviewselected)
{
InitializeComponent();
textBox1.Text = strListviewselected;
}
Related
I have an application that allows the users to upload the selected images to the DataGridView and perform operations on their. However, when multiple images are selected, the Form freezes until the image information is uploaded to the DataGridView. I have tried BackgroundWorker for this, but it didn't work either. My codes look like this:
private void button1_Click(object sender, EventArgs e)
{
var file = new OpenFileDialog
{
Filter = #"TIFF |*.tiff| TIF|*.tif",
FilterIndex = 1,
Title = #"Select TIFF file(s)...",
Multiselect = true
};
if (file.ShowDialog() == DialogResult.OK)
{
Listing(file.FileNames);
}
}
private void Listing(string[] files)
{
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
if (file != null)
{
// Image from file
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length;
//Create the new row first and get the index of the new row
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["name"].Value = pic_name;
row.Cells["sizes"].Value = pic_sizes + " pixels";
row.Cells["size"].Value = pic_size + " bytes";
}
}
}
How can I solve this problem?
EDIT: After Alex's comment, I tried like this:
private void button1_Click(object sender, EventArgs e)
{
var file = new OpenFileDialog
{
Filter = #"TIFF |*.tiff| TIF|*.tif",
FilterIndex = 1,
Title = #"Select TIFF file(s)...",
Multiselect = true
};
if (file.ShowDialog() == DialogResult.OK)
{
_ = Test(file.FileNames);
}
}
private async Task Test(string[] s)
{
await Task.Run(() => Listing(s));
}
private void Listing(string[] files)
{
BeginInvoke((MethodInvoker) delegate
{
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
if (file != null)
{
// Image from file
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length;
//Create the new row first and get the index of the new row
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["name"].Value = pic_name;
row.Cells["sizes"].Value = pic_sizes + " pixels";
row.Cells["size"].Value = pic_size + " bytes";
}
}
});
}
But unfortunately the result is same.
I think the whole problem is in collecting image datas. Because a ready list will not take longer to load if it will not need extra processing. For this reason, I prepared a scenario like below.
private readonly BindingList<Tiff> _tiffs = new BindingList<Tiff>();
private void button1_Click(object sender, EventArgs e)
{
Listing();
}
private void Listing()
{
foreach (var f in _tiffs)
{
if (f != null)
{
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["ColName"].Value = f.ColName;
row.Cells["ColSizes"].Value = f.ColSizes + " pixels";
row.Cells["ColSize"].Value = f.ColSize + " bytes";
}
}
}
public static List<string> Files(string dir, string ext = "*.tiff")
{
var DirInfo = new DirectoryInfo(dir);
return DirInfo.EnumerateFiles(ext, SearchOption.TopDirectoryOnly).Select(x => x.FullName).ToList();
}
public void SetSource()
{
// Source folder of images...
var files = Files(#"___SOURCE_DIR___");
var total = files.Count;
var i = 1;
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length.ToString();
_tiffs.Add(new Tiff(pic_name, pic_sizes, pic_size));
BeginInvoke((MethodInvoker)delegate
{
label1.Text = $#"{i} of {total} is added to the BindingList.";
});
i++;
}
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
SetSource();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Set something if you want.
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Set something if you want.
}
public class Tiff
{
public Tiff(string name, string sizes, string size)
{
ColName = name;
ColSizes = sizes;
ColSize = size;
}
public string ColName { get; set; }
public string ColSizes { get; set; }
public string ColSize { get; set; }
}
And here is the result:
[UPDATE: Added Form1() constructor]
I am trying to match some data from certain clases into combo box values in windows form application.
What I've done until now looks like this:
(This class has some region[] values that I want to store in a combobox, depending on enum Project)
public Form1()
{
formatWorker.DoWork += worker_DoWork;
formatWorker.RunWorkerCompleted += worker_RunWorkerCompleted;
extractWorker.DoWork += extractWorker_DoWork;
extractWorker.ProgressChanged += extractWorker_ProgressChanged;
extractWorker.RunWorkerCompleted += extractWorker_RunWorkerCompleted;
InitializeComponent();
projectBox.DataSource = Constant.projects.ToString();
projectBox.SelectedIndex = (int)Regions.Project.NBTevo;
PopulateUsbDevices();
}
class Regions
{
public enum Project
{
NBT = 0,
NBTevo = 1,
MGU = 2
}
string[] regions = { "ARG", "AUSNZ", "ECE", "IND", "ISR", "LA", "ME", "NA", "NAF", "NANT", "PAL", "SEA", "TC", "ZA" };
public string[] GetRegionsForProject(Project proj)
{
//all directories from /Databases/proj[i]
string[] allDirectories = Constant.ExtractFileNames(Directory.GetDirectories(Constant.path + "//" + Constant.projects[(int)proj]));
string[] availableSubDirectories = Enumerable.Intersect(allDirectories, regions).ToArray();
return availableSubDirectories;
}
}
The next class stores a certain pattern files
class DBVersion
{
public string[] GetVersion(string proj, string region)
{
string pattern = "^" + proj + "_" + region + "_" + #"(\d+\.\d+\.\d+_[a-zA-Z0-9_]+)\.iso$";
string[] files = Directory.GetFiles(Constant.path + "\\" + proj + "\\" + region + "\\images\\", "*.iso", SearchOption.AllDirectories);
return files;
}
}
I am trying to build a dependency, for example, depending on the selected values in projectBox and regionBox some versions will appear in versionBox
private void projectBox_SelectedIndexChanged(object sender, EventArgs e)
{
isoPaths.Clear();
populateRegions((Regions.Project)Enum.Parse(typeof(Regions.Project), projectBox.SelectedValue.ToString()));
regionBox.SelectedIndex = 0;
regionBox_SelectedIndexChanged(null, null);
}
private void regionBox_SelectedIndexChanged(object sender, EventArgs e)
{
string[] versionPaths = version.GetVersion(projectBox.SelectedValue.ToString(), regionBox.SelectedItem.ToString());
isoPaths.Clear();
isoPaths.AddRange(versionPaths);
populateVersions(Constant.ExtractFileNames(versionPaths));
//versionBox.SelectedIndex = 0;
//versionBox_SelectedIndexChanged(null, null);
}
private void versionBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void populateRegions(Regions.Project proj)
{
this.regionBox.DataSource = region.GetRegionsForProject(proj);
}
private void populateVersions(string[] versions)
{
this.versionBox.DataSource = version.GetVersion(
projectBox.SelectedItem.ToString(),
regionBox.SelectedItem.ToString());
}
After running, I don't have nothing stored in ComboBox
If you want to bind a DataSource to a ComboBox you should use :
An object that implements the IList interface or an Array
according to the ComboBox.DataSource Property documentation
So this line in the constructor of Form1:
projectBox.DataSource = Constant.projects.ToString();
has to be changed into this:
projectBox.DataSource = Constant.projects;
The rest of the comboboxes is empty because the problem cascades from one to the next. If one is empty then the rest cannot be filled appropriately
Basicly i have contextmenustrip and listview and i add functions to the context menustrip like delete update etc but i dont want this menu open without click and select any item in listview how can i do it ?
#region listview fonksiyonları
listView1.FullRowSelect = true;
listView1.View = View.Details;
listView1.Columns.Add("Versiyon No", 133, HorizontalAlignment.Left);
listView1.Columns.Add("Açıklama", 200, HorizontalAlignment.Left);
listView1.Columns.Add("Tarih", 154, HorizontalAlignment.Left);
#endregion
#region listviewde txt dosyalarını gösterme
string[] dosyalar = System.IO.Directory.GetFiles(masaustu + "\\Versiyonlar");
string k = "";
int deger = 0;
foreach (var item in dosyalar)
{
ListViewItem lili = new ListViewItem();
deger=item.LastIndexOf("\\");
k = item.Remove(0,deger);
k = k.Remove(0, 1);
lili.Text = k;
StreamReader oku = new StreamReader(masaustu + "\\" + "Versiyonlar" + "\\" + k);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[] { ";", "$" }, StringSplitOptions.RemoveEmptyEntries);
lili.SubItems.Add(dizi[0]);
lili.SubItems.Add(dizi[1]);
listView1.Items.Add(lili);
}
}
#endregion
#region txt içindekileri textboxda göstermek
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
liste frm = new liste();
try
{
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(masaustu + "\\" + "Versiyonlar" + "\\" + a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
textBox1.Text = OkunanVeri;
}
oku.Close();
}
catch
{
}
}
this is listview codes i am not sure if that can help you but you might want to check it out
You can subscribe the opening event of ContextMenuStrip and if there is no selection in your listview set e.Cancel to true which will prevent the contextmenu from opening.
Look at https://msdn.microsoft.com/de-de/library/ms229721(v=vs.110).aspx for more details!
You have a ContextMenuStrip cms where you add a eventhandler either in Windows forms designer or in Code
cms.Opening += new System.ComponentModel.CancelEventHandler(this.cms_Opening);
Inside your eventhandler you check if you got an item in your listview selected to determine if you want your contextmenu open or closed.
void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
// This event handler is invoked when the ContextMenuStrip
// control's Opening event is raised.
// Set Cancel to true to prevent the cms to be opened.
e.Cancel = listView1.Selected == null;
}
So if you got an selected item in your listView1 your contextmenu will be opened otherwise it won't show.
I have a listview with subitems. The first 5 sub items are the name, items, total price, address and telephone.
The rest of the subitems contain the past list that I displayed for my order.
It is a pizzeria program and I want it to be able to get the customers info and order.
I can get the info but can't get the rest of the order.
I'm wondering how I can display the rest of my order if that makes sense.
Example Order:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
-Bacon
BreadSticks
Right now my messagebox looks like this:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
So I just want it to display the -Bacon and BreadSticks.
Source Code:
private void CustomerInfo_Click(object sender, EventArgs e)
{
ListViewItem customers = new ListViewItem(fullName.Text);
customers.SubItems.Add(totalcount.ToString());
customers.SubItems.Add(total.ToString());
customers.SubItems.Add(Address.Text);
customers.SubItems.Add(telephone.Text);
for (int i = 0; i < OrderlistBox.Items.Count; i++)
{
customers.SubItems.Add(OrderlistBox.Items[i].ToString());
}
Customers.Items.Add(customers);
MessageBox.Show("Sent order for " + fullName.Text.ToString() + " to screen.");
//CLEAR ALL FIELDS
OrderlistBox.Items.Clear();
fullName.Text = "";
Address.Text = "";
telephone.Text = "";
totalDue.Text = "";
totalItems.Text = "";
}
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
MessageBox.Show("Name: " + Customers.SelectedItems[0].SubItems[0].Text + "\n" +
"Adress: " + Customers.SelectedItems[0].SubItems[3].Text + "\n" +
"Telephone: " + Customers.SelectedItems[0].SubItems[4].Text + "\n" +
"Order: " +Customers.SelectedItems[0].SubItems[5].Text);
}
}
You can create custom message box by creating new winform that act as your messagebox.
Create public property on it to pass the value of your selecteditems something like:
Then on your form :
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MyFormMessageDialog
{
name = Customers.SelectedItems[0].SubItems[0].Text,
adress=Customers.SelectedItems[0].SubItems[3].Text,
telephone=Customers.SelectedItems[0].SubItems[4].Text
};
myformmessagedialog.ShowDialog();
}
}
Your MessageBoxDialogform:
MyFormMessageDialog : Form
{
public MyFormMessageDialog()
{
InitializeComponent();
}
public string name;
public string adress;
public string telephone;
private void MyFormMessageDialog_Load(object sender, EventArgs e)
{
lblName.Text = name;
lbladdress.Text = adress;
telephone.Text telephone;
//if you are saving ado.net stuff
//query username where name = name then bind it on a list box or a combo box
var Orderdata = //you retrieve info via DataTable;
lstOder.Items.Clear();
foreach (DataRow data in Orderdata.Rows)
{
var lvi = new ListViewItem(data["Order"].ToString());
// Add the list items to the ListView
lstlstOder.Items.Add(lvi);
}
}
}
Hope this help you.
Regards
How do I print specified rows out to a file from a DataGridView?
Also how can I print out certain columns?
This is what I have been trying to work with.. but it is not working..:
private void saveButton_Click(object sender, EventArgs e)
{
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveFile1.RestoreDirectory = true;
if (saveFile1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile1.FileName);
List<string> theList = new List<string>();
foreach (var line in theFinalDGV.Rows)
{
if (line.ToString().Contains("FUJI"))
richTextBox1.AppendText(line + "\n");
}
}
}
Can anyone help me in the right direction?
DataGridViewRow.ToString() only gives you the typename back, not the row content. You can use this extender to get the rowcontent ('ColumnName'):
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
DataGridView dgv = dgvr.DataGridView;
foreach (DataGridViewCell cell in dgvr.Cells) {
DataGridViewColumn col = cell.OwningColumn;
output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
}
return output;
}
}
if you only want the content of the row without the coulmn-headername use this (space separated):
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
foreach (DataGridViewCell cell in dgvr.Cells) {
output += cell.Value.ToString() + " ";
}
return output.TrimEnd();
}
}
your code will look like this:
class YourClass
{
private void saveButton_Click(object sender, EventArgs e)
{
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveFile1.RestoreDirectory = true;
if (saveFile1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile1.FileName);
List<string> theList = new List<string>();
foreach (var line in theFinalDGV.Rows)
{
string linecontent = line.RowToString();
if (linecontent.Contains("FUJI"))
richTextBox1.AppendText(linecontent + "\n");
}
}
}
}
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
DataGridView dgv = dgvr.DataGridView;
foreach (DataGridViewCell cell in dgvr.Cells) {
DataGridViewColumn col = cell.OwningColumn;
output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
}
return output;
}
}