i have an issue on Visual Studio(wpf) with the listbox.
If i want to insert or delete some data from the database, then they are working,but the listbox will just be refreshed if i'm clicking the menuitem for once. I think this is due to the load method, but why isn't it refreshing the data?
This is my XAML-Code:
<UserControl x:Class="WpfApplication1.AutorenBearbeiten"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="300" Loaded="UserControl_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="28*" />
<ColumnDefinition Width="36*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Medien" Grid.ColumnSpan="2"
FontSize="16" />
<ListBox x:Name="box" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=at_nachname}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{Binding ElementName=box,Path=SelectedItem}" Grid.Column="1" Grid.Row="1" >
<TextBlock Text="Autoren_id" />
<TextBox Text="{Binding Path=at_id}" MaxLength="5"/>
<TextBlock Text="Vorname" />
<TextBox Text="{Binding Path=at_vorname}" MaxLength="30"/>
<TextBlock Text="Nachname" />
<TextBox Text="{Binding Path=at_nachname}" MaxLength="30"/>
<TextBlock Text="Geburtsdatum" />
<TextBox MaxLength="30" Text="{Binding Path=at_gebDatum, StringFormat=dd.MM.yyyy}" />
<Button Name="speichern" Height="23" Margin="4" Click="speichern_Click">Änderungen speichern</Button>
<Button Name="loeschen" Height="23" Margin="4" Click="loeschen_Click">Löschen</Button>
<StackPanel DataContext="{Binding ElementName=box}" Grid.Column="1" Grid.Row="1" >
<TextBlock Text="Autoren_id" />
<TextBox x:Name="id" MaxLength="5"/>
<TextBlock Text="Vorname" />
<TextBox x:Name="vorname" MaxLength="30"/>
<TextBlock Text="Nachname" />
<TextBox x:Name="nachname" MaxLength="30"/>
<TextBlock Text="Geburtsdatum" />
<TextBox x:Name="datum" MaxLength="30"/>
<Button x:Name="neubutton" Height="23" Margin="4" Click="neu_Click">Neu</Button>
<TextBlock Name="submitfehler" FontWeight="Bold" Foreground="Red" />
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
And this is the xaml.cs file :
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApplication1
{
/// <summary>
/// Interaction logic for AutorenBearbeiten.xaml
/// </summary>
public partial class AutorenBearbeiten : UserControl
{
libraryEntities6 db = new libraryEntities6();
public AutorenBearbeiten()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var erg = db.a_autor;
erg.Load();
box.ItemsSource = erg.Local.OrderBy(m => m.at_id);
box.ItemsSource =
(from m in db.a_autor
orderby m.at_id
select m).ToList();
}
private void speichern_Click(object sender, RoutedEventArgs e)
{
try
{
db.SaveChanges();
}
catch(Exception e1)
{
submitfehler.Text = e1.Message;
}
}
private void loeschen_Click(object sender, RoutedEventArgs e)
{
a_autor am = (a_autor)box.SelectedItem;
if (am != null)
{
db.a_autor.Remove(am);
db.SaveChanges();
box.Items.Refresh();
}
}
private void neu_Click(object sender, RoutedEventArgs e)
{
a_autor autor = new a_autor();
autor.at_id = id.Text;
autor.at_vorname = vorname.Text;
autor.at_nachname = nachname.Text;
autor.at_gebDatum = Convert.ToDateTime(datum.Text);
//s1.s_k_klasse = liklassen.SelectedValue.ToString() setzt die Klasse via foreign key
//db.schuelers.AddObject(s1);
db.a_autor.Add(autor);
box.Items.Refresh();
/*
((klassen))liklassen.SelectedItem).schuelers.Add(s1); //setzt die klasse durch zuweisen zum nav.Property
lischueler.Items.Refresh(); //nötig weil das navigational seit ER 5 nicht observable ist
*/
}
}
}
A Picture from the window is below:
Window
There is no magic connection between the ListBox and the database so when you are calling the Add or Remove method of the DbContext the ListBox won't be affected.
What you should do is to set the ItemsSource property of the ListBox to an ObservableCollection<a_autor> and then call the Add/Remove method of this one besides calling the Add/Remove method of the DbContext:
System.Collections.ObjectModel.ObservableCollection<a_autor> _sourceCollection;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var erg = db.a_autor;
erg.Load();
_sourceCollection = new System.Collections.ObjectModel.ObservableCollection<a_autor>((from m in db.a_autor
orderby m.at_id
select m).ToList());
box.ItemsSource = _sourceCollection;
}
private void loeschen_Click(object sender, RoutedEventArgs e)
{
a_autor am = (a_autor)box.SelectedItem;
if (am != null)
{
_sourceCollection.Remove(am);
db.a_autor.Remove(am);
db.SaveChanges();
box.Items.Refresh();
}
}
private void neu_Click(object sender, RoutedEventArgs e)
{
a_autor autor = new a_autor();
autor.at_id = id.Text;
autor.at_vorname = vorname.Text;
autor.at_nachname = nachname.Text;
autor.at_gebDatum = Convert.ToDateTime(datum.Text);
_sourceCollection.Add(autor);
db.a_autor.Add(autor);
box.Items.Refresh();
}
You can create an ObservableCollection instead of binding to the List. ObservableCollection implements INotifyPropertyChanged so it can send a notification whenever something is changed in the container.
Also, I would suggest you to try
public void RefreshListBox()
{
box.ItemsSource =
(from m in db.a_autor
orderby m.at_id
select m).ToList();
}
and call this after db.SaveChanges()
You should use MVVM pattern instead of code behind and use property changes. First result in Google:
https://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level
I hope it helps you.
Juan
Related
I designed a window with WPF, and so I used a lot of Labels. My question now is, if it is possible to get all Labels that are named like this: lblinch, lblinch1, lblinch2 ... .
Personally, I would like to store them in an array or in an arraylist. The Labels are not in the same parent-element except for "Window" and the first "Grid".
<Label Content="inch" Name="lblinch2" Grid.Row="0" Grid.Column="2" />
<Label Content="Distance between Beams Manual Input" Grid.Row="1" Grid.Column="0" />
<TextBox Name="tbDistanceBeamsManualInput" Width="{x:Static local:Constants.TOOL_WIDTH}" Grid.Row="1" Grid.Column="1" Margin="0,5,0,5" Background="Yellow" />
<Label Content="inch" Name="lblinch3" Grid.Row="1" Grid.Column="2" />
<Label Content="Bolt Hole Center to Column Wall * =" Grid.Row="2" Grid.Column="0" />
<TextBox Name="tbBHoleCenterToColumnWall" Width="{x:Static local:Constants.TOOL_WIDTH}" Grid.Row="2" Grid.Column="1" Margin="0,5,0,5" Background="Yellow" />
<Label Content="inch" Grid.Row="2" Name="lblinch4" Grid.Column="2" />
Here's what I'm doing to find controls of a specific type with a part of their x:Name:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApp4
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
//find labels that have "lbl" in their name
var labels = GetControlsByName<Label>(LabelsContainer, "lbl", new List<Label>());
//do something with them
foreach (var label in labels)
{
Console.WriteLine(label.Name);
}
}
private List<T> GetControlsByName<T>(Visual root, string nameSearchTerm, List<T> result) where T : FrameworkElement
{
var childrenCount = VisualTreeHelper.GetChildrenCount(root);
for (var i = 0; i < childrenCount; i++)
{
var childVisual = (Visual)VisualTreeHelper.GetChild(root, i);
if (childVisual is T control && control.Name.Contains(nameSearchTerm))
{
result.Add(control);
}
GetControlsByName(childVisual, nameSearchTerm, result);
}
return result;
}
}
}
XAML
<Window
x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp4"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid x:Name="LabelsContainer">
<Label x:Name="lbl1" />
<TextBlock x:Name="tbl1" />
<Label x:Name="lbl2" />
<Label x:Name="lbl3" />
</Grid>
</Window>
First, name your parent Grid. ("RootGrid" in this case.)
<Grid x:Name="RootGrid">
<Label x:Name="lblinch1" />
<TextBlock />
<Label x:Name="lblinch2" />
<TextBox />
<Label x:Name="lblinch3" />
<Button />
<Label x:Name="lblinch4" />
<Label x:Name="lblinch5" />
</Grid>
Then use the VisualTreeHelper to get the children and filter them by their names.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private List<Label> LabelControls { get; } = new();
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
int count = VisualTreeHelper.GetChildrenCount(this.RootGrid);
for (int i = 0; i < count; i++)
{
if (VisualTreeHelper.GetChild(this.RootGrid, i) is Label label &&
label.Name.StartsWith("lblinch") is true)
{
LabelControls.Add(label);
}
}
}
}
I want the MediaElement called player to play mp3 after specify its source:
private void Button_Click_2(object sender, RoutedEventArgs e)
{
player.Stop();
player.Source = new Uri("ms-appx:///Assets/anata.mp3");
player.Play();
}
But it does not work, and there is no Error showed. How should I do?
Here is the original question and full code:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:cvt="using:App1"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<cvt:MusicConverter x:Key="mc"/>
</Page.Resources>
<Viewbox Visibility="Visible" Margin="20">
<Grid x:Name="root" Height="1000" Width="1800">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2.5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="0.15*"/>
<RowDefinition Height="0.15*"/>
</Grid.RowDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Height="150" Fill="#FF4187A9" VerticalAlignment="Top"/>
<MediaElement x:Name="player" MediaFailed="player_MediaFailed" Grid.Column="1" Grid.Row="0" Margin="20" VerticalAlignment="Center" Source="Assets/bad_apple.mp4" AutoPlay="false" MediaOpened="Player_Opened" MediaEnded="Player_ended"/>
<Slider x:Name="controller" Value="{Binding ElementName=player, Path=Position, Converter={StaticResource mc}, Mode=TwoWay}" Grid.Column="1" Grid.Row="1" Height="50" Width="1000" Minimum="0" Maximum="100" VerticalAlignment="Center" />
<Button RequestedTheme="Dark" FontFamily="Segoe MDL2 Assets" Content="" Grid.Column="1" Grid.Row="2" Height="75" Width="75" Margin="449,0,0,0" Click="Button_Click_3"/>
<Button RequestedTheme="Dark" FontFamily="Segoe MDL2 Assets" Content="" Grid.Column="1" Grid.Row="2" Height="75" Width="75" Margin="750,0,0,0" Click="Button_Click_2"/>
<Button x:Name="playButton" RequestedTheme="Dark" Grid.Column="1" Grid.Row="2" Height="75" Width="75" HorizontalAlignment="Center" Click="Button_Click_1">
<SymbolIcon x:Name="ppp" Symbol="Play" />
</Button>
<Slider x:Name="vol" StepFrequency="0.05" Minimum="0.0" Maximum="1.0" SmallChange="0.05" LargeChange="0.1" Value="0.5" Grid.Column="1" Grid.Row="2" Height="30" Width="100" Margin="1019,42,167,43" ValueChanged="Slider_ValueChanged"/>
<ToggleSwitch x:Name="repeatButton" Grid.Row="2" Grid.Column="1" OnContent="repeat on" OffContent="repeat off" IsOn="False" Margin="45,0,0,0"/>
<TextBlock Grid.Row="0" Grid.Column="0" VerticalAlignment="Top" Text="PlayList" FontSize="72" Grid.ColumnSpan="2" Margin="140,27,1146,0"/>
<Rectangle Grid.Row="0" Grid.Column="1" Margin="20" StrokeThickness="2" Stroke="#ffffff"/>
<ListBox x:Name="lst" SelectedIndex="0" Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" Margin="0,155,0,0" SelectionChanged="ListBox_SelectionChanged">
<TextBlock Text="Bad Apple" FontSize="50" />
<TextBlock Text="Anata" FontSize="50" />
<TextBlock Text="Wind" FontSize="50" />
</ListBox>
</Grid>
</Viewbox>
</Page>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace App1
{
class MusicConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return ((TimeSpan)value).TotalSeconds;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return TimeSpan.FromSeconds((double)value);
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
MediaElement mediaElement = new MediaElement();
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("button");
mediaElement.SetSource(stream, stream.ContentType);
mediaElement.Play();
}
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int sel = lst.SelectedIndex;
string videoName;
switch (sel)
{
case 0:
videoName = "bad_apple.mp4"; break;
case 1:
videoName = "anata.mp3"; break;
case 2:
videoName = "Wind.mp3"; break;
default:
videoName = "bad_apple.mp4"; break;
}
player.Source = new Uri("ms-appx:///Assets/" + videoName);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (player.CurrentState.ToString()=="Paused")
{
player.Play();
ppp.Symbol = Windows.UI.Xaml.Controls.Symbol.Pause;
Debug.WriteLine(player.CurrentState.ToString());
}
else
{
player.Pause();
ppp.Symbol = Windows.UI.Xaml.Controls.Symbol.Play;
Debug.WriteLine(player.CurrentState.ToString());
}
}
private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
player.Volume = (double)vol.Value;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
lst.SelectedIndex = (lst.SelectedIndex + 1) % lst.Items.Count;
Debug.WriteLine(player.CurrentState.ToString());
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
lst.SelectedIndex = (lst.SelectedIndex - 1) < 0 ? lst.Items.Count - 1 : lst.SelectedIndex - 1;
}
private void Player_Opened(object sender, RoutedEventArgs e)
{
controller.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
}
private void Player_ended(object sender, RoutedEventArgs e)
{
if (repeatButton.IsOn)
{
player.Play();
}
else
{
lst.SelectedIndex = (lst.SelectedIndex + 1) % lst.Items.Count;
int sel = lst.SelectedIndex;
string videoName;
switch (sel)
{
case 0:
videoName = "bad_apple.mp4"; break;
case 1:
videoName = "anata.mp3"; break;
case 2:
videoName = "Wind.mp3"; break;
default:
videoName = "bad_apple.mp4"; break;
}
player.Source = new Uri("ms-appx:///Assets/" + videoName);
player.Play();
}
player.Play();
}
private void player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
string msg = e.ErrorMessage;
Debug.WriteLine(msg);
}
}
}
The main question is Player_ended. I want this player can repeat when the repeatButton is on, and play next mp3 automatically when it is off. But it can't work. The Source is changed to new Uri successfully, but the code player.Play() seems like to be ignored. I must click playButton to play. I simplify the code and I get a new question, which is showed on the top.
Please check the following:
Check if the computer has sound turned on
Check whether the music file URL is correct (and whether the file can be played by other players)
If everything is normal, you can listen to the MediaElement.MediaFailed event. If it triggers, it indicates that the music file may be abnormal. You can get more information about the error from the event.
private void player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
string msg = e.ErrorMessage;
Debug.WriteLine(msg);
}
By the way, in Windows 10, build 1607 and on we recommend that you use MediaPlayerElement in place of MediaElement. MediaPlayerElement has the same functionality as MediaElement, while also enabling more advanced media playback scenarios. Additionally, all future improvements in media playback will happen in MediaPlayerElement.
Update
The problem with your code is that you are calling Play() method at the wrong time.
After setting the Source for the player, the player will enter the Opening state. When you call Play() while the player is in this state, the player cannot play audio, and when the music file is loaded, it naturally enters the Pause state.
So you can delete the player.Play() method at the end of Player_ended, just set player.AutoPlay = True;
like this:
private void Player_ended(object sender, RoutedEventArgs e)
{
if (repeatButton.IsOn)
{
player.Play();
}
else
{
lst.SelectedIndex = (lst.SelectedIndex + 1) % lst.Items.Count;
player.AutoPlay = true;
}
}
By the way, When you modify lst.SelectedIndex, the ListBox_SelectionChanged event is also triggered, you do not have to call it again in Player_ended.
Best regards.
I want to customize my listbox or listview to behave like the control on the following picture:
It's similar to FlipView but I've never worked with FlipView before and just saw some pictures.
I have found a good solution for me. It might helps somebody. I've changed it a little bit and It works perfectly for me.
http://www.codeproject.com/Articles/741026/WPF-FlipView
Try something like this
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<UserControl.Resources>
<DataTemplate x:Key="Test">
<Grid >
<Border Background="Red"
Loaded="RedBorder_OnLoaded" >
<!--content for this card goes here-->
<TextBlock Text="{Binding}"></TextBlock>
</Border>
<Border Background="Green"
Loaded="GreenBorder_OnLoaded"
Visibility="Collapsed" >
<!--content for this card goes here-->
<TextBlock Text="{Binding}"></TextBlock>
</Border>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox Name="myListbox"
Margin="50"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
ItemTemplate="{StaticResource Test}" />
<StackPanel Grid.Row="1"
HorizontalAlignment="Center"
Orientation="Horizontal">
<Button Width="20"
Height="20"
Background="Black"
Click="FirstButton_OnClick" />
<Button Width="20"
Height="20"
Background="Black"
Click="SecondButton_OnClick" />
</StackPanel>
</Grid>
</UserControl>
code behind
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class UserControl1 : UserControl
{
private readonly List<Border> redBorders = new List<Border>();
private readonly List<Border> greenBorders = new List<Border>();
public UserControl1()
{
InitializeComponent();
myListbox.ItemsSource = new List<string>() { "Batman", "Superman", "All others" };
}
private void RedBorder_OnLoaded(object sender, RoutedEventArgs e)
{
redBorders.Add(sender as Border);
}
private void GreenBorder_OnLoaded(object sender, RoutedEventArgs e)
{
greenBorders.Add(sender as Border);
}
private void FirstButton_OnClick(object sender, RoutedEventArgs e)
{
redBorders.ForEach(p => p.Visibility = Visibility.Visible);
greenBorders.ForEach(p => p.Visibility = Visibility.Collapsed);
}
private void SecondButton_OnClick(object sender, RoutedEventArgs e)
{
redBorders.ForEach(p => p.Visibility = Visibility.Collapsed);
greenBorders.ForEach(p => p.Visibility = Visibility.Visible);
}
}
}
usage
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1">
<wpfApplication1:UserControl1 />
it's pretty simple, but i guess you can improve it from here.
I'm using c# and WPF web application and I want to build a simple form which contains two text boxes for user input (name and phone number) and a "send" button. when the user clicks on the send button it will redirect to an other page and will display (with textblock) the entered values.
I tried to read about data binding, but still didn't success to make it work.
1. How do I save the entered values into a variable ?
2. How do I call these variables from the second page and display the saved text ?
Hope for help, thanks!
xaml code of the form:
<TextBlock Height="20" Width="120" Margin="36,43,144,237">enter details:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,69,224,211">Name:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,103,224,177">Phone:</TextBlock>
<!--textboxes-->
<TextBox Height="20" Width="95" Margin="100,69,104,211" Name="getName" Background="Gray"/>
<TextBox Height="20" Width="95" Margin="100,103,105,177" Name="getPhoneNumber" Background="Gray"/>
<!-- -->
<Button Height="20" Width="50" Margin="218,103,32,177" Name="sendButton" Click="sendButton_Click">send</Button>
what should be the code behind ? i simply want to display the entered values on an other page with textblock.
this is the function i use to redirect to the "result page":
public void sendButton_Click(object sender, RoutedEventArgs e)
{
Submit();
}
void Submit()
{
Page2 resultpage = new Page2();
NavigationService.Navigate(resultpage);
}
Edit:
Ok I succeed to make it work thanks to Mike's answer.
Thanks Mike, for other users this how the code looks like now:
form page xaml code:
<TextBlock Height="20" Width="120" Margin="36,43,144,237">enter details:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,69,224,211">Name:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,103,224,177">Phone:</TextBlock>
<!--textboxes-->
<TextBox Height="20" Width="95" Margin="100,69,104,211" Name="getName" Background="Gray"/>
<TextBox Height="20" Width="95" Margin="100,103,105,177" Name="getPhoneNumber" Background="Gray"/>
<!-- -->
<Button Height="20" Width="50" Margin="218,103,32,177" Name="sendButton" Click="sendButton_Click">send</Button>
form page c# behind code:
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
public void sendButton_Click(object sender, RoutedEventArgs e)
{
Submit();
}
void Submit()
{
Page2 resultpage = new Page2(getName.Text, getPhoneNumber.Text);
NavigationService.Navigate(resultpage);
}
}
result page xaml code:
<Grid>
<TextBlock x:Name="showName" Height="50" Width="100" Margin="65,125,73,125" Text="{Binding ElementName=showName, Path=Text}" />
</Grid>
result page c# code behind:
public Page2(string name, string phoneNumber)
{
InitializeComponent();
showName.Text = name;
}
Thanks again Mike :)
Ok here is what I would do. You can create arguments in the constructor of your Page2:
public Page2(string name, string phoneNumber)
{
//login to handle name and phone number
}
On your first page you can just pass name and phone number using the Name property in the xaml.
void Submit()
{
Page2 resultpage = new Page2(getName.Text, getPhoneNumber.Text);
NavigationService.Navigate(resultpage);
}
<Page x:Class="Login.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="253" d:DesignWidth="276"
Title="Page1" Background="Blue">
<Grid>
<TextBlock Text="Prince jain" HorizontalAlignment="Left" VerticalAlignment="Top" Height="50" Width="100" Margin="48,0,0,0" FontSize="40"></TextBlock>
<TextBlock Height="50" FontSize="18" HorizontalAlignment="Left" Margin="6,141,0,0" Name="txtnavigatevalue" Text="Test Navigation" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="134,144,0,0" Name="txtnavigation" VerticalAlignment="Top" Width="130" />
<Button Content="Check" Height="23" HorizontalAlignment="Left" Margin="134,187,0,0" Name="buttoncheck" VerticalAlignment="Top" Width="75" Click="buttoncheck_Click" />
</Grid>
</Page>
<Page x:Class="Login.Page2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup- compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page2" Background="BlueViolet">
<Grid>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="46,94,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="198" />
</Grid>
</Page>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
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 Login
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void buttoncheck_Click(object sender, RoutedEventArgs e)
{
Page2 p2 = new Page2();
p2.textBlock1.Text = txtnavigation.Text;
//txtnavigatevalue.Text = "";
NavigationService.Navigate(p2);
}
}
}
private void buttoncheck_Click(object sender, RoutedEventArgs e)
{
Page2 p2 = new Page2();
p2.textBlock1.Text = txtnavigation.Text;
//txtnavigatevalue.Text = "";
NavigationService.Navigate(p2);
}
here are the codes, i would like that the tabcontrol allow the change in the datagrid to be displayed/but it doesnot work.
note without this tabcontrol datagrid displayed the change on view/delete
NOTE
please study the tab "VIEW/DELETE DATA" when delete click, let the datagrid refresh.
xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightClient.ServiceReference1;
namespace SilverlightClient
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
//onsubmit button clicked
//insert operation
DemoServiceClient webService = new DemoServiceClient();
webService.InsertDataCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webService_InsertDataCompleted);
webService.InsertDataAsync(TestItem1TxtBox.Text, TestItem2TxtBox.Text);
}
void webService_InsertDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
//throw new NotImplementedException();
return;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//onget button clicked
//select operation
DemoServiceClient webService = new DemoServiceClient();
webService.GetRowsCompleted += new EventHandler<GetRowsCompletedEventArgs>(webService_GetRowsCompleted);
//results returned by this cannot be used directly
//as the method works asynchronously thereby allowing
//to proceed before the results are generated.
//there must do anything regarding results
//using the completed event handler
webService.GetRowsAsync();
}
void webService_GetRowsCompleted(object sender, GetRowsCompletedEventArgs e)
{
// ResultsGrid.ItemsSource = e.Result;
ResultsGrid.ItemsSource = null;
List<Table1> gamma= e.Result.ToList();
ResultsGrid.ItemsSource = gamma;
tabControl1.UpdateLayout();
// tabControl1.TabIndex = 1;
}
private void OnDeleteClick(object sender, RoutedEventArgs e)
{
//remove operation
Table1 selectedRow = ResultsGrid.SelectedItem as Table1;
// Now access the service to delete the item
DemoServiceClient webService = new DemoServiceClient();
webService.DeleteRowAsync(selectedRow.KEY);
// Now refresh the grid
webService.GetRowsCompleted += new EventHandler<GetRowsCompletedEventArgs>(webService_GetRowsCompleted);
webService.GetRowsAsync();
}
private void button4_Click(object sender, RoutedEventArgs e)
{
//UPDATE BUTTON
//get the selected row
Table1 selectedRow = ResultsGrid.SelectedItem as Table1;
//declare the web service
DemoServiceClient webService = new DemoServiceClient();
//call the update method
//do pass the GUID and the UPDATE text
webService.UpdateDataAsync(selectedRow.KEY, textBox1.Text);
//assign the event handler
webService.GetRowsCompleted += new EventHandler<GetRowsCompletedEventArgs>(webService_GetRowsCompleted);
//call get rows
webService.GetRowsAsync();
}
}
}
xaml
<UserControl x:Class="SilverlightClient.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="600" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White" Height="600" Width="600">
<Grid.RowDefinitions>
<RowDefinition Height="20*" />
<RowDefinition Height="555*" />
<RowDefinition Height="25*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="66*" />
<ColumnDefinition Width="468*" />
<ColumnDefinition Width="66*" />
</Grid.ColumnDefinitions>
<sdk:TabControl Grid.Column="1" Grid.Row="1" Height="555" HorizontalAlignment="Left" Name="tabControl1" VerticalAlignment="Top" Width="468" BorderThickness="0,2,0,0">
<sdk:TabItem Header="Insert Data" Name="tabItem1" FontFamily="Trebuchet MS">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="328*" />
<ColumnDefinition Width="128*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="65*" />
<RowDefinition Height="74*" />
<RowDefinition Height="22*" />
<RowDefinition Height="122*" />
<RowDefinition Height="235*" />
</Grid.RowDefinitions>
<sdk:Label Height="64" HorizontalAlignment="Left" Margin="2,1,0,0" Name="label1" VerticalAlignment="Top" Width="106" Content="TestItem1" Grid.Column="1" />
<TextBox Height="52" Margin="0,1,4,0" x:Name="TestItem1TxtBox" VerticalAlignment="Top"/>
<sdk:Label Height="64" HorizontalAlignment="Left" Margin="2,0,0,0" Name="label2" VerticalAlignment="Top" Width="106" Content="TestItem2" Grid.Row="1" Grid.Column="1" />
<TextBox Height="64" x:Name="TestItem2TxtBox" VerticalAlignment="Top" Margin="0,0,4,0" Grid.Row="1" />
<Button Content="Submit" Height="23" Name="button2" Width="133" Click="button2_Click" Margin="191,0,4,121" Grid.Row="2" Grid.RowSpan="2" />
<TextBox Grid.Row="3" Height="121" HorizontalAlignment="Left" Name="textBox1" VerticalAlignment="Top" Width="325" />
<TextBlock Grid.Column="1" Grid.Row="3" Height="121" HorizontalAlignment="Left" Name="textBlock1" Text="Update Text for TEXT item 2, please select guig key by using the VIEW/DELETE DATA TAB" VerticalAlignment="Top" Width="123" TextWrapping="Wrap" />
</Grid>
</sdk:TabItem>
<sdk:TabItem x:Name="TABview" Header="View/Delete Data">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="29*" />
<RowDefinition Height="155*" />
<RowDefinition Height="24*" />
<RowDefinition Height="27*" />
<RowDefinition Height="286*" />
</Grid.RowDefinitions>
<sdk:Label HorizontalAlignment="Left" Name="label3" VerticalAlignment="Stretch" Width="173" Content="Datagrid Silverlight" Margin="0,3,0,0" />
<sdk:DataGrid AutoGenerateColumns="True" Height="155" HorizontalAlignment="Left" Name="ResultsGrid" VerticalAlignment="Top" Width="456" Cursor="Hand" GridLinesVisibility="All" Grid.Row="1" />
<Button Content="Get" Height="23" HorizontalAlignment="Left" Margin="135,2,0,0" Name="button1" VerticalAlignment="Top" Width="149" Click="button1_Click" />
<Button Content="Delete" Height="26" HorizontalAlignment="Left" Margin="381,0,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="OnDeleteClick" />
<Button Content="Update" Grid.Row="3" Height="27" HorizontalAlignment="Left" Margin="320,0,0,0" Name="button4" VerticalAlignment="Top" Width="132" Click="button4_Click" />
</Grid>
</sdk:TabItem>
</sdk:TabControl>
</Grid>
</UserControl>
demoservice.svc.cs
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
namespace WcfSqlDemoWeb
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// Return the list of valid data
[OperationContract]
public List<Table1> GetRows()
{
DataClasses1DataContext db = new DataClasses1DataContext();
var selected_rows = from rows in db.Table1s select rows;
return selected_rows.ToList();
}
// Insert a new data into the database
[OperationContract]
public void InsertData(string testItem1,
string testItem2)
{
DataClasses1DataContext db = new DataClasses1DataContext();
// Create a new row object.
Table1 row = new Table1
{
KEY = Guid.NewGuid(),
TestItem1 = testItem1,
TestItem2 = testItem2
};
// Add the new object to the collection.
db.Table1s.InsertOnSubmit(row);
// Submit the change to the database.
db.SubmitChanges();
db.Dispose();
return;
}
[OperationContract]
public void UpdateData(Guid key, string update_text)
{
DataClasses1DataContext db = new DataClasses1DataContext();
// get the row with the key as a single tuple
var original_row = (from rows in db.Table1s where rows.KEY == key select rows).Single();
// get the row with the key
var delete_row = from rows in db.Table1s where rows.KEY == key select rows;
//a new instance of the table
//assiging it values as needed
Table1 changed_table = new Table1
{
KEY = key,
TestItem1 = original_row.TestItem1,
TestItem2 = update_text
};
//delete the row completely with the original selected record
db.Table1s.DeleteAllOnSubmit(delete_row);
//now insert the newly created TABLE INSTANCE
db.Table1s.InsertOnSubmit(changed_table);
// Submit the change to the database.
db.SubmitChanges();
}//update data ends
// Delete the item specified by the passed key
[OperationContract]
public void DeleteRow(Guid key)
{
DataClasses1DataContext db = new DataClasses1DataContext();
var selected_row = from rows in db.Table1s where rows.KEY == key select rows;
// Delete the selected "rows". There will actual be only one
// item in this collection because the Guid is unique and is the
// primary key for the table.
db.Table1s.DeleteAllOnSubmit(selected_row);
// Submit the change to the database.
db.SubmitChanges();
}
/*
//here it will give a error message stating,
//the sql return type is not serializable
//please make a datacontract and then try.
//so simply put, support for this type of data handling is being
//removed
// sql select all
[OperationContract]
public SqlDataReader sqlSELECT()
{
string connectionstring = #"Data Source=DEVELOPMENT-PC\SQLEXPRESS;Initial Catalog=SILVERLIGHT;Integrated Security=True;Pooling=False";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connectionstring;
SqlCommand command = new SqlCommand();
command.CommandText = "select * from Table1";
command.CommandType = CommandType.Text;
command.Connection = connection;
connection.Open();
var results_by_sql = command.ExecuteReader();
return results_by_sql;
}
*/
// Add more operations here and mark them with [OperationContract]
}
}
Try this... it is not an answer to your specific problem, but just a quick way to get it working in a way that could be considered "better". It uses binding with a notifying property to supply your grid with data. I've only included the relevant bits of code that you would need to change, you can fill in the rest.
namespace SilverlightClient
{
public partial class MainPage : UserControl, INotifyPropertyChanged
{
public MainPage()
{
InitializeComponent();
this.dataContext = this;
}
void webService_GetRowsCompleted(object sender, GetRowsCompletedEventArgs e)
{
MyResults = e.Result.ToList();
tabControl1.UpdateLayout();
}
protected List<Table1> MyResults
{
get { return _myResults; }
set
{
if (_myResults != value)
{
_myResults = value;
OnPropertyChanged("MyResults");
}
}
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArg(propertyName));
}
private List<Table1> _myResults = null;
public event PropertyChangedEventHandler PropertyChanged;
}
}
<sdk:DataGrid Name="ResultsGrid"
... etc ...
DataContext="MyResults"
/>