Windows Form Application and
Window Presentation Foundation (WPF) are almost identical in some controls and
coding style either Visual Basic or C# developer, but their some instances that
both of them has their own advantages depends the users need. In this
tutorials, I’ll show you a simple way how to add items in listbox when the user
click add button and automatically add in a listbox list, I am using C# in WPF,
this code also run in Windows Form Application.
Here is the source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF_My_First_Apps
{
/// <summary>
/// Interaction logic for
MainWindow.xaml
/// </summary>
public partial class MainWindow :
Window
{
string name, address;//I
declared this variable as public
//so that it will use when it call
//name and address value when the users
//click listbox item.
public MainWindow()
{
InitializeComponent();
}
private void
btnOk_Click(object sender, RoutedEventArgs e)
{
name = txtname.Text;
address = txtaddress.Text;
listBox1.Items.Add(name);
listBox1.Items.Add(address);
}
private void
listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int select;
select = listBox1.SelectedIndex;
switch (select)
{
case 0:
MessageBox.Show("You click name: " + name);
break;
case 1:
MessageBox.Show("You click Address: " + address);
break;
}
}
}
}
Sample screenshot:
To count the number items listed
in the listbox, here is the code.
int count;
count = listBox1.Items.Count;
MessageBox.Show(count.ToString());
To add item in listbox using
checkbox, here is the code:
private void checkBox1_Checked(object sender, RoutedEventArgs
e)
{
if (checkBox1.IsChecked == true)
{
listBox1.Items.Add("Banana");
}
}
private void
checkBox2_Checked(object sender, RoutedEventArgs e)
{
if (checkBox1.IsChecked == true)
{
listBox1.Items.Add("Orange");
}
}
private void checkBox3_Checked(object
sender, RoutedEventArgs e)
{
if (checkBox1.IsChecked == true)
{
listBox1.Items.Add("Grapes");
}
}
To clear items in listbox, here
is the code:
listBox1.Items.Clear();
checkBox1.IsChecked = false;
checkBox2.IsChecked = false;
checkBox3.IsChecked = false;
0 comments:
Post a Comment