Add item to Listview control - c#

I have a listview in c# with three columns and the view is details. I need to add a item to each specific column but I am having a hard time with this. I have tried several things. Here is what I got so far. Thanks for any help in advance.
// Add the pet to our listview
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(pet.Name);
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);

I have done it like this and it seems to work:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
}
}

The first column actually refers to Text Field:
// Add the pet to our listview
ListViewItem lvi = new ListViewItem();
lvi.text = pet.Name;
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);
Or you can use the Constructor
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
....

Add items:
arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Retrieve items:
productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;
source code

Simple one, just do like this..
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);

Very Simple
private void button1_Click(object sender, EventArgs e)
{
ListViewItem item = new ListViewItem();
item.SubItems.Add(textBox2.Text);
item.SubItems.Add(textBox3.Text);
item.SubItems.Add(textBox4.Text);
listView1.Items.Add(item);
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
}
You can also Do this stuff...
ListViewItem item = new ListViewItem();
item.SubItems.Add("Santosh");
item.SubItems.Add("26");
item.SubItems.Add("India");

The ListView control uses the Items collection to add items to listview in the control and is able to customize items.

Related

DropDown Default slected value in Windows Form Application when DropDown Bind with data source

I bind a ComboBox with a data source it shows the datasource in the dropdown but I want a default selected value.
Example:
"Select" is selected by default like shown in this picture.
In my Case result are show like this
This is my code:
public void BindComboBoxItem()
{
try
{
ItemRepository repo = new ItemRepository();
List<Item> items = repo.GetAll();
cbxSelectItem.DataSource = items;
cbxSelectItem.DisplayMember = "Name";
cbxSelectItem.ValueMember = "Id";
}
catch (Exception ex)
{
MessageBox.Show(MessageResource.ErrorMessage, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If you want to have "Select" as your default selected value then you need to add it in your items and set
cbxSelectItem.SelectedIndex = //input the index of "Select"
which is 0 in the case of your first image link.
By setting the DropDownStyle the ComboBox always has a value selected. If you do not want this behavior you can only use the last line.
//This makes it so you have to select a value from the list, there is also 1 auto selected
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
//This makes sure we're selecting the value we want
comboBox.SelectedIndex = comboBox.Items.IndexOf( "value" );
If you want to add an item to tell people to select a value you can do this:
comboBox.Items.Insert(0, "Please select any value");
Note* this creates a selectable item, if you don't want this you can do this:
private void comboBox_TextChanged(object sender, EventArgs e)
{
if(comboBox.SelectedIndex <= 0)
{
comboBox.Text = "Please select a value";
}
}
private void Form_Load(object sender, EventArgs e)
{
comboBox.Text = "Please select a value";
}
It can be done using Key pair my code is here
private void BindComboBoxItem()
{
ItemRepository repo = new ItemRepository();
List<Item> items = repo.GetAll();
List<KeyValuePair<int, string>> allitems = new List<KeyValuePair<int, string>>();
KeyValuePair<int, string> first = new KeyValuePair<int, string>(0, "Please Select");
allitems.Add(first);
foreach (Item item in items)
{
KeyValuePair<int, string> obj = new KeyValuePair<int, string>(item.Id, item.Name);
allitems.Add(obj);
}
cbxSelectItem.DataSource = allitems;
cbxSelectItem.DisplayMember = "Value";
cbxSelectItem.ValueMember = "Key";
}

Retrieving TextBlock Tag Within ListBox WP

im trying to get the value of a textblock in a listbox when the item is selected
public MainPage()
{
Startup.checknetwork();
InitializeComponent();
this.Loaded += new RoutedEventHandler(Load_List);
}
private void Load_List(object sender, RoutedEventArgs e)
{
XDocument loadedData = XDocument.Load("List.xml");
List<XElement> elements = loadedData.Descendants("ItemTitle").ToList();
List<RSSItem> aux = new List<RSSItem>();
foreach (XElement rssItem in elements)
{
RSSItem rss = new RSSItem();
rss.Title1 = rssItem.Element("Title").Value;
rss.Date1 = rssItem.Element("Uri").Value;
aux.Add(rss);
TextBlock One = new TextBlock();
One.Text = rss.Title1;
One.Tag = rss.Date1;
AListBox.Items.Add(One);
}
}
private void AList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var SelectedItem = ((TextBlock)sender).Tag as String;
}
everything loads up fine using debug.writeline it shows the correct textbox texts and tags the alist shows the list.
how ever if i select an item i just get an error
Could someone tell me what i am doing wrong
thanks
The SelectionChanged event send by ItemsControl. So the sender is ItemsControl not a selected item. You need SelectedItem not the sender.

combobox Autocomplete doesn't work

I want to create a auto complete tools using combobox.
So i just add some items to my combobox .And set these items as a source of my combobox.
In form_load i do this:
private void frmInvoice_Load(object sender, EventArgs e)
{
comboBox1.AutoCompleteMode=AutoCompleteMode.Append;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
But it doesn't work and when i type a letter the whole word doesn't appear in combobox.Why ?
i follow this link :http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
best regards.
Since you've declared CustomSource for auto completion, you should provide that source:
private void frmInvoice_Load(object sender, EventArgs e)
{
comboBox1.AutoCompleteMode=AutoCompleteMode.Append;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
// Put here the auto completions' e.g.
data.Add("My String 1");
data.Add("Autocompletion 2");
data.Add("Some stuff");
comboBox1.AutoCompleteCustomSource = data;
}
You didn't upload your CustomSource.
public Form1()
{
InitializeComponent();
this.comboBox1.AutoCompleteCustomSource.AddRange
(new string[] {"Raj Beniwal", "Rohit Malhotra", "Ronit Singh", "Ravi Kumar",
"Rohit Behl", "Sanjay Singh", "Shalini Singh", "Seema Malhotra", "Savi Verma",
"Karan Kappor", "Kapil Malhotra", "Vikash Nanda", "Vikram Jain", "Amit Garg",
"Atul Wadhwani", "Ashwani Pandey"
});
this.comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this.comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
Refference from : http://www.c-sharpcorner.com/Blogs/2050/autocomplete-combobox-in-visual-C-Sharp-2010.aspx
What I have done is use a 3rd party dlls. These are of Telerik. My code is as follows
<telerik:RadComboBox x:Name="radComboBox" VerticalAlignment="Top" Visibility="Visible" AllowDrop="True"
ItemsSource="{Binding AvailList}" SelectedItem="{Binding SelectedComboboxItem, Mode=TwoWay}"
IsEditable="True"
telerik:TextSearch.TextPath="DisplayName" Height="17" Margin="10,34,39,0" />
This is in xaml. It directly reads from the ItemSource and does the autocompletion.
Or you can do this...
private void LoadStuffNames()
{
try
{
string Query = "select stuff_name from dbo.stuff";
string[] names = GetColumnData_FromDB(Query);
comboName.AutoCompleteMode = AutoCompleteMode.Suggest;
comboName.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection x = new AutoCompleteStringCollection();
if (names != null && names.Length > 0)
foreach (string s in names)
x.Add(s);
comboName.AutoCompleteCustomSource = x;
}
catch (Exception ex)
{
}
finally
{
}
}
Cheers..

Listview as a log file

Hi. I have a Windows form application. After I do something, what I want is to put updates in the Listview. More like a log file. Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
//Add column header
listView1.Columns.Add("Import Status", 100);
listView1.Columns.Add("Price", 70);
listView1.Columns.Add("Date", 70);
//Add items in the listview
string[] arr = new string[4];
ListViewItem itm;
//Add first item
arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
//Add second item
arr[0] = "product_2";
arr[1] = "200";
arr[2] = "20";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}
How can I Add items to the ListView without 'hardcoding' them? Any suggestions? How can I do that every Button.Click, it can add rows with some data in it?
How can I Add items to the ListView without 'hardcoding' them?
Code
private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Import Status");
listView1.Columns.Add("Price");
listView1.Columns.Add("Date");
}
private void btnAdd_Click(object sender, EventArgs e)
{
ListViewItem LVI = new ListViewItem(txtstatus.Text);
LVI.SubItems.Add(txtPrice.Text);
LVI.SubItems.Add(txtDate.Text);
listView1.Items.Add(LVI);
}
UI
Globalize your these two lines to allow your access in every method of your class:
string[] arr = new string[4];
ListViewItem itm;
Now create a button click event and put your code in it:
private void button1_Click(object sender, EventArgs e)
{
arr[0] = "product_2"; //you can get these values from textboxes if you are taking input from user
arr[1] = "200";
arr[2] = "20";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}
hi there :) you could use a datagridview instead of the listview control.
all you have to do is to define an own dataset or add a dataset control
to your project. u just need to add your three columns to a new datatable in there.
then:
add that dataset to your form, it will appear in your form code
set the datasource of the datagridview to the added dataset
now you can add new datarows to the datatable and they will appear in the datagridview automatically. the good thing is, you have to define your table layout once and the designer will generate you a custom datarow type, what you can use.
my experience told me, that this way is more comfortable than using listview. the main thing is, u can LINQ over the datatable if you want to process data from there in other
context. i used listview before, but since datagridview in combination with dataset, everything is better ;)
sincerly,
ceth

How to add new item into listbox that using datasource?

I create a winform application that contains 3 textbox (pcno, pcname and pcipadd), one listbox that is using a datasource and one button to add new item. I'm having a trouble to add an item to my listbox. I'm using this code on the add item button:
_pcno.Add(new PCNo() { PCNO = pcno.Text,
PCNAME = pcname.Text,
IPADDRESS = pcipadd.Text });
The code above adds the new item successfully, but the selected item in the listbox also been updated.
In details, I currently have a "PCN01" on my listbox. Then I go to my textbox (pcno.text) then write new value (example "PC02") and click the button to add item .What happens is the item is added but the "PC01" are also getting updated to "PC02". After reloading the form (re-open) all change back to normal, "PC01" with its value and "PC02" with its value. I just don't want the selected item on the listbox getting update while adding the new item. Any ideas?
Ok, to put this simplly, this is what I'm trying to do, you can try it, if you add new item the selected item also getting updated:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace PCListing
{
public partial class Form1 : Form
{
private BindingList<mylist> _pcno;
private ListBox listBox1;
private TextBox pcno;
private TextBox pcname;
private Button btnAdd;
public Form1()
{
InitializeComponent();
FlowLayoutPanel layout = new FlowLayoutPanel();
layout.Dock = DockStyle.Fill;
Controls.Add(layout);
listBox1 = new ListBox();
layout.Controls.Add(listBox1);
pcno = new TextBox();
layout.Controls.Add(pcno);
pcname = new TextBox();
layout.Controls.Add(pcname);
btnAdd = new Button();
btnAdd.Click += btnAdd_Click;
btnAdd.Text = "Add Item";
layout.Controls.Add(btnAdd);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
_pcno = new BindingList<mylist>();
_pcno.Add(new mylist() { pcno = "1", pcname = "PC01" });
_pcno.Add(new mylist() { pcno = "2", pcname = "PC02" });
listBox1.DisplayMember = "pcno";
listBox1.DataSource = _pcno;
pcno.DataBindings.Add("Text", _pcno, "pcno");
pcname.DataBindings.Add("Text", _pcno, "pcname");
}
private void btnAdd_Click(object sender, EventArgs e)
{
_pcno.Add(new mylist() { pcno =pcno.Text, pcname = pcname.Text });
}
public class mylist
{
public string pcname { get; set; }
public string pcno { get; set; }
}
}
}
The problem is caused by TextBox databindings.
pcno.DataBindings.Add("Text", _pcno, "pcno");
pcname.DataBindings.Add("Text", _pcno, "pcname");
In that form DataSource is updated when you edit values in text boxes.
You might consider changing those lines to:
pcno.DataBindings.Add("Text", _pcno, "pcno", false, DataSourceUpdateMode.Never);
pcname.DataBindings.Add("Text", _pcno, "pcname", false, DataSourceUpdateMode.Never);

Categories