I have a WPF application with a number of comboboxes that tie together. When I switch comboboxx #1, combobox #2 switches, etc.
Here is the xaml for the 2 comboboxes:
<ComboBox Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,12,286,0" ItemsSource="{Binding}" Name="CboDivision" VerticalAlignment="Top" Width="120" SelectionChanged="CboDivision_SelectionChanged" />
<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,9,32,0" Name="CboCustomerList" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" SelectionChanged="CboCustomerList_SelectionChanged" Grid.Row="1" />
CboDivision gets populated at the beginning and doesnt need a reset. HEre is the code that calls the change in division, which should trigger a change in customer:
private void CboDivision_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
division = CboDivision.SelectedValue.ToString();
CboCustomerList.ItemsSource = null;
BackgroundWorker customerWorker = new BackgroundWorker();
customerWorker.DoWork += new DoWorkEventHandler(FillCustomers);
customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(customerWorker_RunWorkerCompleted);
FillCustomers(null, null);
}
When I do an index change it calls a backgroundworker which calls the following code:
private void FillCustomers(object sender, DoWorkEventArgs e)
{
string connectionString = Settings.Default.ProdConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand SqlCmd = new SqlCommand();
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.Parameters.Add("#division", SqlDbType.NVarChar).Value = division;
SqlCmd.Connection = connection;
SqlCmd.CommandText = "sp_GetCustomers";
SqlDataReader reader = null;
connection.Open();
reader = SqlCmd.ExecuteReader();
List<string> result = new List<string>();
while (reader.Read())
{
result.Add(reader["NAME"].ToString());
}
e.Result = result;
}
The problem is that i am unable to switch selections on CboDivision and have CboCustomerList clear and reload new values into it. Is it the way I'm binding the values in the xaml?
How can I have a change in CboDivision cause a clearing of CboCustomerList items, then the execution of the filling routine?
i am currently resetting the combobox with:
CboCustomerList.SelectedIndex = -1;
but this just appends the new cbocustomerlist query to the end
I also tried
CboCustomerList.Items.Clear()
but that just returns a null reference error after the box is refilled and the user selects an item.
Well, you didn't post all of your code, but one problem is that you are not invoking your worker thread.
Replace FillCustomers(null, null) with customerWorker.RunWorkerAsync().
private void CboDivision_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
division = CboDivision.SelectedValue.ToString();
CboCustomerList.ItemsSource = null;
BackgroundWorker customerWorker = new BackgroundWorker();
customerWorker.DoWork += new DoWorkEventHandler(FillCustomers);
customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(customerWorker_RunWorkerCompleted);
customerWorker.RunWorkerAsync(); // <-- this
}
Let me know if this helps. If there is still more problem, please post the rest of your code.
There are details of code you didn't show. However, here is an example that works: two combos, what that is populated at the beginning, and a second that is populated each time the selection changes in the first. Notice that the data is fetched in a background worker, just as in your case.
XAML
<Window x:Class="CombosRefresh.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ComboBox Name="CboDivisions" ItemsSource="{Binding}" Grid.Row="0" Margin="5" />
<ComboBox Name="CboList" ItemsSource="{Binding}" Grid.Row="1" Margin="5" />
</Grid>
</Window>
C#
public partial class MainWindow : Window
{
private BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
CboDivisions.DataContext = new List<string>() { "red", "blue", "green" };
CboDivisions.SelectionChanged += CboDivisions_SelectionChanged;
bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
}
void CboDivisions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var division = CboDivisions.SelectedValue as string;
bw.RunWorkerAsync(division);
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
CboList.DataContext = e.Result as List<string>;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
var division = e.Argument as string;
var r = new Random();
var result = new List<string>();
for(int i = 0; i < r.Next(0, 10); ++i)
{
result.Add(string.Format("{0} #{1}", division, i+1));
}
e.Result = result;
}
}
replace the wrong FillCustomers(null, null); code
with: customerWorker.RunWorkerAsync();
Related
I am trying to make an auction application for my course.
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
var dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = interval;
dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
dt.Stop();
}
else
ts(count);
};
ts(count);
dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
This is main page you need to login. I read data from database. The problem is when I press bid button many times it is just resetting, but in background is working on. What do I need to do?
<Window x:Class="Auction.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="800">
<Grid Margin="0,148,0,3" Name="myGrid" Background="#FF00286E">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="29*"/>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Left" Height="66" Margin="0,-68,0,0" VerticalAlignment="Top"
Width="792" Background="#FF00286E" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="12*"/>
<ColumnDefinition Width="13*"/>
</Grid.ColumnDefinitions>
<Button Content="Login" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogin" Click="btnLogin_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
<Button Content="Logout" Grid.Column="1" HorizontalAlignment="Left" Margin="300,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogout" Click="btnLogout_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
<Grid HorizontalAlignment="Left" Height="78" Margin="0,-146,0,0" VerticalAlignment="Top" Width="792"
Grid.ColumnSpan="2" Background="#FF98BFD4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="769*"/>
<ColumnDefinition Width="31*"/>
</Grid.ColumnDefinitions>
<Label Content="Welcome to Auction Application. Please Login to bid!" HorizontalAlignment="Center" Margin="44,28,0,0" VerticalAlignment="Top"
Height="40" Width="748" BorderThickness="3" FontSize="18" FontWeight="Bold" FontFamily="Verdana" Background="#FF98BFD4" Grid.ColumnSpan="2"/>
</Grid>
<Button Content="Bid" Grid.Column="1" HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" Width="103" Height="29" FontSize="20" FontFamily="Verdana" FontStyle="Italic"
FontWeight="ExtraBold" Click="Button_Click" Name="btnBid"/>
<Button Content="Add User" Grid.Column="1" HorizontalAlignment="Left" Margin="10,255,0,0"
VerticalAlignment="Top" Width="103" Height="31" Name="btnAdd" Click="btnAdd_Click"/>
<DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"
Height="298" Width="502" Name="dataGrid1" ItemsSource="{Binding}"
SelectionChanged="DataGrid_SelectionChanged" AlternatingRowBackground="Coral">
</DataGrid>
<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="48" Margin="10,119,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="144" Name="tb" FontSize="20" FontWeight="Bold" FontStyle="Italic" IsReadOnly="True"/>
</Grid>
</Window>
If I understand correctly, each time the user clicks the Bid button, you need to reset the timer. However, the previous timer continues. I haven't pasted your code into a project to test, but it appears to me that you need to make the dispatch timer a class field or property like this:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
Inside the event handler for Bid, stop the current _dt first followed by instantiating the new timer:
_dt.Stop();
_dt = new System.Windows.Threading.DispatcherTimer();
Try this change:
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Class level field:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
this._dt.Stop();
this._dt = new System.Windows.Threading.DispatcherTimer();
this._dt.Interval = interval;
this._dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
this._dt.Stop();
}
else
ts(count);
};
ts(count);
this._dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
I have this longListSelector:
<phone:LongListSelector
x:Name="ListaMensajesTablon"
ItemsSource="{Binding Mensajes}"
ItemTemplate="{StaticResource MensajesTablonDataTemplate}"
SelectionChanged="MensajeTablonSelected"/>
With this ItemTemplate:
<DataTemplate x:Key="MensajesTablonDataTemplate">
<Grid>
<Button MaxHeight="85" MaxWidth="95" MinHeight="85" MinWidth="95" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Click="Button_Click" BorderBrush="Transparent">
<Button.Content>
<Image x:Name="imagenFav" MaxHeight="75" MaxWidth="75" MinHeight="75" MinWidth="75"
Source="{Binding userFav, Converter={StaticResource BoolToHeart}}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Button.Content>
</Button>
</Grid>
</DataTemplate>
This code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
botonFavPulsado = true;
botonAmor = (Button)sender;
}
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
}
}
I want to do is that when you press a button that is inside an element of LongListSelector change the picture . The first time I press the button enters in the function Button_Click and then enters in the function MensajeTablonSelected function and change the image (good). The problem is the second time I press the same button is entering in the function Button_Click function and does not enter in the function MensajeTablonSelected
Resume : ToggleButton in LongItemSelector working the first time but not the second one
Problem solved:
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if (((LongListSelector)sender).SelectedItem != null)
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
//Unselect ITEM
((LongListSelector)sender).SelectedItem = null;
}
}
This solution have a problem, the function MensajeTablonSelected is called again.
I have a Windows phone application which gets a list of photos URLs from a SQL database depending what it uploaded.
The issue i have is users can add their own photos to that list but it does not refresh the list on the page so i added a refresh to re run the code but it still does not run.
Well the code runs but does not update the list box.
//get/clean these strings
int parkID = 0;
string parkName = string.Empty;
public photos()
{
InitializeComponent();
BuildLocalizedApplicationBar();
}
private void ThemeParkPhotos_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
//No errors have been passed now need to take this file and parse it
//Its in XML format
XDocument xdox = XDocument.Parse(e.Result);
//need a list for them to be put in to
List<Photos> themeparkPhoto = new List<Photos>();
themeparkPhoto.Clear();
XNamespace ns = "http://schemas.datacontract.org/2004/07/WCFServiceWebRole1";
//Now need to get every element and add it to the list
foreach (XElement item in xdox.Descendants(ns + "Photos"))
{
Photos content = new Photos();
content.ID = Convert.ToInt32(item.Element(ns + "ID").Value);
content.PhotoURL = Convert.ToString(item.Element(ns + "PhotoURL").Value);
//content.ID = Convert.ToInt32(item.Element(ns + "id").Value);
//content.ThemeParkName = item.Element(ns + "name").Value.ToString();
themeparkPhoto.Add(content);
}
ThemeParkPhoto.ItemsSource = null;
ThemeParkPhoto.ItemsSource = themeparkPhoto.ToList();
//Delete all the stuff
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
//There an Error
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//This is to get the data that was passed from the home screen to which song to use!
base.OnNavigatedTo(e);
if ((NavigationContext.QueryString["pID"] == string.Empty) || (NavigationContext.QueryString["pName"] == string.Empty))
{
//if not show message box.
MessageBox.Show("Empty Vaules have been sent, Please got back and try again");
}
else
{
parkID = Convert.ToInt32(NavigationContext.QueryString["pID"]);
parkName = NavigationContext.QueryString["pName"].ToString();
PageName.Text = parkName;
GetThemeParkPhotos();
}
}
public void GetThemeParkPhotos()
{
WebClient ThemeParkPhotos = new WebClient();
ThemeParkPhotos.DownloadStringCompleted += ThemeParkPhotos_DownloadStringCompleted;
ThemeParkPhotos.DownloadStringAsync(new Uri("HIDDEDURL/viewphotos?format=xml&themeparkid=" + parkID));
//MessageBox.Show("Test if this works"+parkID);
}
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Default;
ApplicationBar.Opacity = 1.0;
ApplicationBar.IsVisible = true;
ApplicationBar.IsMenuEnabled = true;
ApplicationBarIconButton AddButton = new ApplicationBarIconButton();
AddButton.IconUri = new Uri("/Images/add.png", UriKind.Relative);
AddButton.Text = "Add Photo";
ApplicationBar.Buttons.Add(AddButton);
AddButton.Click +=AddButton_Click;
//Dont add refresh button as it does not work at this time :(
ApplicationBarIconButton RefreshButton = new ApplicationBarIconButton();
RefreshButton.IconUri = new Uri("/Images/refresh.png", UriKind.Relative);
RefreshButton.Text = "Refresh";
ApplicationBar.Buttons.Add(RefreshButton);
RefreshButton.Click += RefreshButton_Click;
}
private void RefreshButton_Click(object sender, EventArgs e)
{
GetThemeParkPhotos();
}
private void AddButton_Click(object sender, EventArgs e)
{
//need to send them to add a photo page with details.
NavigationService.Navigate(new Uri("/TakePhoto.xaml?pID=" + parkID + "&pName=" + parkName, UriKind.Relative));
}
Here the Code for the ListBox
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="559" HorizontalAlignment="Left" Margin="6,20,0,0" x:Name="ThemeParkPhoto" VerticalAlignment="Top" Width="444" FontSize="30" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock x:Name="ID" Text="{Binding ID}"></TextBlock>
<Image x:Name="PhotoURL" Source="{Binding PhotoURL}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I have removed the URL to save the API, That code does run and fill it but why does it not refresh the List Box correctly?
Many Thanks
Thank to being sent here : C# WebClient disable cache
Turns out that Windows phone web client caches the file meaning it never download it again until the app is refreshed. By using a random number generator and adding it to the then of the URL it will always download the file allowing for a refresh.
I have a listbox like this:
<toolkit:ListPicker Name="lstBoxBaseUnitOfMeasure" Width="100" Margin="0,4,0,0">
<toolkit:ListPicker.Items>
<TextBlock Text="EACH" Height="30"/>
<TextBlock Text="GRAM" Height="30"/>
</toolkit:ListPicker.Items>
</toolkit:ListPicker>
I would like to send selected item to Local Database like this:
private void AddProduct_Click(object sender, RoutedEventArgs e)
{
TblProductsToOrder newProductToOrder = new TblProductsToOrder
{
OrderNId = selectedID,
Quantity = int.Parse(txtQuantity.Text),
**BaseUnitOfMeasure = ??????????????**
};
}
ListPicker fires an event,SelectionChanged whenever a item is selected. You will need to listen to that event
<toolkit:ListPicker Name="lstBoxBaseUnitOfMeasure" Width="100" Margin="0,4,0,0" SelectionChanged="listPicker_SelectionChanged">
<toolkit:ListPicker.Items>
<TextBlock Text="EACH" Height="30"/>
<TextBlock Text="GRAM" Height="30"/>
</toolkit:ListPicker.Items>
</toolkit:ListPicker>
private void listPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstBoxBaseUnitOfMeasure.SelectedItem != null)
{
var texBlock = (TextBlock) lstBoxBaseUnitOfMeasure.SelectedItem;
selectedUnit = texBlock.Text;
TblProductsToOrder newProductToOrder = new TblProductsToOrder
{
OrderNId = selectedID,
Quantity = int.Parse(txtQuantity.Text),
BaseUnitOfMeasure = selectedUnit
};
}
}
Assuming that BaseUnitOfMeasure property is of type String, you can try this way :
String selectedUnit = "";
if(lstBoxBaseUnitOfMeasure.SelectedItem != null)
{
var selectedTextBlock = (TextBlock)lstBoxBaseUnitOfMeasure.SelectedItem;
selectedUnit = selectedTextBlock.Text;
}
TblProductsToOrder newProductToOrder = new TblProductsToOrder
{
OrderNId = selectedID,
Quantity = int.Parse(txtQuantity.Text),
BaseUnitOfMeasure = selectedUnit
};
i want to add search panel in my datagrid, there is no error in code but if i enter any value it is not showing any output. Can you please answer my question. my code is here below:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
dx:ThemeManager.ThemeName="MetropolisDark"
Title="MainWindow" Height="350" Width="525" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
ResizeMode="CanMinimize" mc:Ignorable="d" Loaded="Window_Loaded" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors">
<Grid Background="#FF333333" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="41,12,0,0" x:Name="textBlock1" Text="Type here" VerticalAlignment="Top" Width="71" />
<TextBox Grid.Row="1" HorizontalAlignment="Left" Margin="139,12,0,246" x:Name="textBox1" Width="233" TextWrapping="NoWrap" TextChanged="textBox1_TextChanged" />
<ListBox Grid.Row="1" Background="LightYellow" Visibility="Collapsed" Height="33" HorizontalAlignment="Left" Margin="220,45,0,0" Name="listBox1" VerticalAlignment="Top" Width="202" />
</Grid>
</Window>
public partial class MainWindow : Window
{
//object used for update data
DataClasses1DataContext objContext = new DataClasses1DataContext();
//object used to update selected row data
Assignment student = null;
IEnumerable eventt_grp1;
public MainWindow()
{
InitializeComponent();
//Database context
//StudentDBDataContext objContext = new StudentDBDataContext();
//Linq to SQL: this is like sql select query
//std is table alias
//objContext.StudentDetails is table from data is seleted
//var result: behaves like DataSet/DataTable
List<Assignment> a = new List<Assignment>();
eventt_grp1 = a.Select(r => new { r.assignment_title }).ToList();
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
//Show message if it has rows
}
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
string typedstring= textBox1.Text;
List<string> autolist= new List<string>();
foreach(string b in eventt_grp1)
{
if(!string.IsNullOrEmpty(textBox1.Text))
{
if(b.StartsWith(typedstring))
{
autolist.Add(b);
}
}
}
if(autolist.Count>0)
{
listBox1.ItemsSource = autolist;
listBox1.Visibility = Visibility.Visible;
}
else if (textBox1.Text.Equals (""))
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
else
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.ItemsSource != null)
{
listBox1.Visibility = Visibility.Collapsed;
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
if (listBox1.SelectedIndex != -1)
{
textBox1.Text = listBox1.SelectedItem.ToString();
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
}
I have attached image of it too! Thank You !
I suggest you to debug flow. It is possible that autolist is empty. Also use this to update datasource:
listBox1.DataSource = null;
listBox1.DataSource = myList;
Hope it helps
EDIT:
hint -> format your code!