|
I've got this code that changes the theme during runtime
private void ApplyTheme()
{
ResourceDictionary resources = null;
string fileName = string.Empty;
switch (SelectedThemeName)
{
case "Black":
fileName = "Theme_Black.xaml";
break;
case "Blue":
fileName = "Theme_Blue.xaml";
break;
}
if (fileName == string.Empty)
{
throw new Exception(string.Format("Resource dictionary for theme name {0} not found", SelectedThemeName));
}
fileName = "..\Themes\" + fileName;
if (!File.Exists(fileName))
{
throw new Exception(string.Format("Theme name {0} not found", SelectedThemeName));
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
resources = (ResourceDictionary)XamlReader.Load(fs);
}
Application.Current.Resources = resources;
}
The problem is that it relies on a physical file to exist at runtime. Is there a better way to do this?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Hello.
I am trying to make a small "book library" application where readers can rent books.
My application is tructured like this: 4 views(with their associated viewmodels). MainWindow is the main view. Inside it i have a content control where i display the other 3 secondary/child views:HomeView, BookManagingView, ReaderManagingView. The default selected view is HomeView, where i have 2 ListViews(for Readers and Books), and some buttons. In my ReaderManagingView i have some textboxes and buttons to add/update/delete readers from database and listview.
The database has 3 tables: Books, Readers, and RentedBooks.
What i am trying to do is: when i add/update/delete users from my database, i want my changes to reflect (almost)instantly in my ListView.
The problem: The changes are visible only after i restart the application. What should i do, so that my Readers ListView updates after i add/update/delete a user?
Here is some code:
HomeView:
<ListView x:Name="listviewReaders" ItemsSource="{Binding ReadersList, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" SelectedItem="{Binding SelectedReader, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="160" Margin="25,23,315,40">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FullName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ReaderManagingView:
<Grid>
<TextBox x:Name="txtBxFullName" HorizontalAlignment="Left" Height="23" Margin="25,27,0,0" TextWrapping="Wrap" Text="{Binding CurrentReader.FullName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtBxSerialNumber" HorizontalAlignment="Left" Height="23" Margin="25,55,0,0" TextWrapping="Wrap" Text="{Binding CurrentReader.SerialNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtBxIdNumber" HorizontalAlignment="Left" Height="23" Margin="25,83,0,0" TextWrapping="Wrap" Text="{Binding CurrentReader.IdNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtBxAdress" HorizontalAlignment="Left" Height="23" Margin="25,111,0,0" TextWrapping="Wrap" Text="{Binding CurrentReader.Adress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtBxAltContactMethods" HorizontalAlignment="Left" Height="23" Margin="25,139,0,0" TextWrapping="Wrap" Text="{Binding CurrentReader.AltContactMethods, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<Button x:Name="btnAddReader" Command="{Binding AddR, UpdateSourceTrigger=PropertyChanged}" Content="Add" HorizontalAlignment="Left" Margin="25,177,0,0" VerticalAlignment="Top" Width="60"/>
<Button x:Name="btnDeleteReader" Command="{Binding DeleteR, UpdateSourceTrigger=PropertyChanged}" Content="Delete" HorizontalAlignment="Left" Margin="155,177,0,0" VerticalAlignment="Top" Width="60"/>
<Button x:Name="btnClearReader" Command="{Binding ClearR, UpdateSourceTrigger=PropertyChanged}" Content="Clear" HorizontalAlignment="Left" Margin="220,177,0,0" VerticalAlignment="Top" Width="60"/>
<Button x:Name="btnEditReader" Command="{Binding EditR, UpdateSourceTrigger=PropertyChanged}" Content="Save" HorizontalAlignment="Left" Margin="90,177,0,0" VerticalAlignment="Top" Width="60"/>
</Grid>
HomeVM:
public class HomeViewModel : ViewModelBase
{
private Reader selectedReader;
private Book selectedBook;
private BookListFilter selectedFilter;
private ObservableCollection<Book> bookList;
private ObservableCollection<Reader> readerList;
private IEnumerable<BookListFilter> bookLstItemSrc;
public HomeViewModel(MainWindowViewModel _mwvm)
{
Mwvm = _mwvm;
SelectedReader = new Reader();
SelectedBook = new Book();
SelectedFilter = BookListFilter.AllBooks;
BookDBDataContext rdb = new BookDBDataContext();
ReadersList = new ObservableCollection<Reader>(rdb.Readers);
GetBookList();
EditReaderSwitch = new DefCommand(EditReaderInfo);
EditBookSwitch = new DefCommand(EditBookInfo);
}
public DefCommand EditReaderSwitch { get; private set; }
public DefCommand EditBookSwitch { get; private set; }
public MainWindowViewModel Mwvm { get; set; }
public ObservableCollection<Reader> ReadersList
{
get { return readerList; }
set
{
if (readerList != value)
{
readerList = value;
RaisePropertyChanged();
}
}
}
ReaderManagingViewModel:
public class ReaderManagingViewModel : ViewModelBase
{
private static Reader currentReader;
public ReaderManagingViewModel(HomeViewModel hvm)
{
if (CurrentReader == null)
CurrentReader = new Reader();
CurrentReader = hvm.SelectedReader;
AddR = new DefCommand(AddReader);
EditR = new DefCommand(UpdateReader);
DeleteR = new DefCommand(DeleteReader);
ClearR = new DefCommand(ClearReaderFields);
}
public Reader CurrentReader
{
get { return currentReader; }
set
{
if (currentReader != value)
{
currentReader = value;
RaisePropertyChanged();
}
}
}
public DefCommand AddR { get; private set; }
public DefCommand EditR { get; private set; }
public DefCommand DeleteR { get; private set; }
public DefCommand ClearR { get; private set; }
private void AddReader()
{
BookDBDataContext db = new BookDBDataContext();
Reader rObj = new Reader();
rObj.FullName = CurrentReader.FullName;
rObj.SerialNumber = CurrentReader.SerialNumber;
rObj.Id = CurrentReader.Id;
rObj.Adress = CurrentReader.Adress;
rObj.AltContactMethods = CurrentReader.AltContactMethods;
try
{
db.Readers.InsertOnSubmit(rObj);
db.Readers.Context.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private void UpdateReader()
{
BookDBDataContext db = new BookDBDataContext();
var qry = from reader in db.Readers
where reader.Id == CurrentReader.Id
select reader;
foreach (Reader r in qry)
{
r.FullName = CurrentReader.FullName;
r.SerialNumber = CurrentReader.SerialNumber;
r.IdNumber = CurrentReader.IdNumber;
r.Adress = CurrentReader.Adress;
r.AltContactMethods = CurrentReader.AltContactMethods;
}
try
{
db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private void DeleteReader()
{
BookDBDataContext db = new BookDBDataContext();
var rbTbl = (from r in db.RentedBooks
where r.ReaderId == CurrentReader.Id
select r);
var rTbl = (from r in db.Readers
where r.Id == CurrentReader.Id
select r).SingleOrDefault();
try
{
foreach (var rbr in rbTbl)
{
db.RentedBooks.DeleteOnSubmit(rbr);
}
db.Readers.DeleteOnSubmit(rTbl);
db.SubmitChanges();
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("deleting");
}}
|
|
|
|
|
The problem is that the context you're using to make the changes has no connection to the ObservableCollection<T> which holds the current list of readers.
You need some way for the ReaderManagingViewModel to notify the HomeViewModel when something changes.
The standard approach would be to use a mediator service:
MVVM Mediator Pattern[^]
A Mediator Prototype for WPF Apps | Josh Smith on WPF[^]
Alternatively, as a "quick-and-dirty" approach, you could store the HomeViewModel instance passed to the ReaderManagingViewModel constructor, and call public methods on that instance to add, update and delete readers from the list.
Depending on your requirements, you could either have a single method to reload the entire list:
public void LoadReaders()
{
using (BookDBDataContext rdb = new BookDBDataContext())
{
ReadersList = new ObservableCollection<Reader>(rdb.Readers);
}
}
Or you could have separate methods to add, update and delete the readers:
public void AddReader(Reader readerToAdd)
{
ReadersList.Add(readerToAdd);
}
public void UpdateReader(Reader readerToUpdate)
{
var reader = ReadersList.FirstOrDefault(r => r.Id == readerToUpdate.Id);
if (reader != null)
{
reader.FullName = readerToUpdate.FullName;
reader.SerialNumber = readerToUpdate.SerialNumber;
reader.IdNumber = readerToUpdate.IdNumber;
reader.Adress = readerToUpdate.Adress;
reader.AltContactMethods = readerToUpdate.AltContactMethods;
}
else
{
ReadersList.Add(readerToUpdate);
}
}
public void DeleteReader(Reader readerToDelete)
{
var readerToRemove = ReadersList.FirstOrDefault(r => r.Id == readerToDelete.Id);
if (readerToRemove != null) ReadersList.Remove(readerToRemove);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank You! I will try that.
|
|
|
|
|
i used the LoadReaders method, and it works.
Thank you very much!
|
|
|
|
|
Anyone know if there's any official MS documentation that visually describes WPF control templates?
Something like this is what I'm after.
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
"A picture paints a thousand words" - which is probably why they're hard to find in M$ documentation!
However - is this what you're after? WPF Graphics Rendering Overview[^] (search for Control Template)
|
|
|
|
|
I was thinking of something where all the parts of the default set of WPF controls is outlined visually.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Ah sorry. Don't think I've ever seen anything "official" along those lines. Best stuff I saw was part of a course and I didn't (couldn't) "grab" it
|
|
|
|
|
Maybe I should write up an article on it
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
The closest the documentation gets to describing the templates lies in this section[^] of the MSDN.
This space for rent
|
|
|
|
|
Here's my control template
<UserControl.Resources>
<pre>
<ControlTemplate x:Key="myTemplate"
TargetType="{x:Type ComboBox}">
<Grid>
<Popup x:Name="PART_Popup"
IsOpen="{TemplateBinding IsDropDownOpen}">
<Button Height="100"
Width="100"
Content="Hello"/>
</Popup>
</Grid>
</ControlTemplate>
and my usage:
<ComboBox Grid.Row="0"
Grid.Column="3"
Background="Red"
x:Name="comboBox"
Width="150"
Template="{Binding StringFormat=myTemplate}">
The ComboBox does not appear. if I remove the Template line it appears.
What am I doing wrong?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
You're using StringFormat. That's, as you would expect, for formatting strings. Try using Template="{StaticResource myTemplate}" instead.
This space for rent
|
|
|
|
|
Well, that was dumb.. Not sure why I had that in there.
This is what I was looking for
<ToggleButton Grid.Row="0"
Grid.Column="3"
Height="20"
Width="17"
Background="Transparent"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay}">
<pre>
<Path x:Name="Arrow"
Data="{StaticResource DownArrowGeometry}"
Fill="Black"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<popup x:name="PART_Popup"
="" allowstransparency="true"
<pre="">
Height="200"
Width="200"
IsOpen="{Binding IsDropDownOpen, Mode=TwoWay}"
PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}"
Placement="Bottom">
<!--My Content here-->
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
modified 20-Apr-17 13:11pm.
|
|
|
|
|
I have this enem
public enum SpanType
{
Minutes,
Hours,
Days,
Weeks,
Months,
Years
}
and I use in in a DP in the control's code behind like this
public static readonly DependencyProperty TimelineSpanTypeProperty =
DependencyProperty.Register("TimelineSpanType",
typeof(SpanType),
typeof(TimeSpanTimeline),
new PropertyMetadata(SpanType.Days, new PropertyChangedCallback(OnTimelineSpanTypeChanged)));
public SpanType TimelineSpanType
{
get { return (SpanType)GetValue(TimelineSpanTypeProperty); }
set { SetValue(TimelineSpanTypeProperty, value); }
}
private static void OnTimelineSpanTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TimeSpanTimeline control = (TimeSpanTimeline)d;
if (!control._internalControl)
{
control.DrawControl();
}
}
The designer shows the error "The default value type does not match the type of the property".
Yet if I run it it works.
Anyone know what's wrong?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Replace SpanType.Days in your PropertyMetadata with default(SpanType)
This space for rent
|
|
|
|
|
I'm working on a timeline control similar to this
How would you create the "thumb" in the center? What control would be best, and how would you style it?
Anyone done anything like this? Any examples?
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
I have a random error that crashes my WPF application. It generally happens when navigating between views. There are numerous try/catch wrappers but it manages to avoid all of these.
This seems to be the most relevant information but I do not know how to research or interpret it. Any suggestions would be appreciated.
<problemsignatures>
<eventtype>CLR20r3
<parameter0>IssuanceUAT.exe
<parameter1>2.0.2.0
<parameter2>58d338db
<parameter3>PresentationFramework
<parameter4>4.6.1055.0
<parameter5>563c1d45
<parameter6>789c
<parameter7>44
<parameter8>System.IO.IOException
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Navigation error to a non existing page.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I have the busiest WPF form I have ever created, 23 combo boxes, 35 text boxes or date pickers and a bunch of buttons and that is just the first tab, there are 10 other tabs with lists and user controls. All user controls are lazy loaded when the tab is selected.
There is a load of automation on the form where 1 action filters/disables 1 or more controls.
I load the data using a BGW thread and that is fast and consistent. The data is loaded into a local object and when the loading is complete I bind the selected object
SelectedObject = LocalObject
The binding is initially resonably fast, sub 1 second, this blows out to 8+ seconds with subsequent page loads. The delay seems to be caused by binding the SelectedObject to the LocalObject (the delay is so huge it can easily be tracked to that line of code).
Any suggestions how I can alleviate the delay problem when binding.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi there,
I have a DataGrid with it's content stored in a List<>. I'm able to format cells depending on the data of ONE other cell using a value converter.
Here is the my MainWindow.xaml:
<Window x:Class="Test_WpfGrid.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test_WpfGrid"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:CBrushConverter x:Key="BrushConverter"/>
</Window.Resources>
<Grid>
<DataGrid x:Name="grdPeople" Margin="5,5,5,5" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="FullRow">
<DataGrid.Columns>
<DataGridTextColumn Width="150" Binding="{Binding FName}" Header="First Name">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding Age, Converter={StaticResource BrushConverter}}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Width="150" Binding="{Binding LName}" Header="Last Name">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding Age, Converter={StaticResource BrushConverter}}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Width="50" Binding="{Binding Age}" Header="Age" />
<DataGridTextColumn Width="50" Binding="{Binding DisplState}" Header="State" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
And this is the MainWindow.xaml.cs:
namespace Test_WpfGrid
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<CPerson> People = new List<CPerson>();
People.Add(new CPerson("John", "Doe", 25, 2));
People.Add(new CPerson("Jane", "Doe", 52, 4));
People.Add(new CPerson("Jenny", "Doe", 14, 0));
People.Add(new CPerson("Sammy", "Doe", 24, 3));
People.Add(new CPerson("Paul", "Smith", 10, 3));
grdPeople.ItemsSource = People;
}
}
}
Data is stored in a List<cperson> with the following class:
namespace Test_WpfGrid
{
public class CPerson
{
public string FName { get; set; }
public string LName { get; set; }
public int Age { get; set; }
public int State { get; set; }
public string DisplState
{
get { return (this.State > 0) ? this.State.ToString() : "undef"; }
}
public CPerson(string FName, string LName, int Age, int State)
{
this.FName = FName;
this.LName = LName;
this.Age = Age;
this.State = State;
}
}
}
And finally here is my value converter class:
namespace Test_WpfGrid
{
public class CBrushConverter : IValueConverter
{
private Color[] mBGColors = { Color.FromArgb(255, 224, 224, 224),
Color.FromArgb(255, 255, 155, 155),
Color.FromArgb(255, 200, 240, 200)
};
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int Age = (int)value;
System.Windows.Media.Brush Brush = new SolidColorBrush(this.mBGColors[(Age >= 18) ? 2 : ((Age >= 12) ? 1 : 0)]);
return Brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
With this code the columns for FName and LName are formated with a specific background color, depending on the value of the Age-property.
Now I want to format the two columns depeding on the values of Age AND State.
Is this possible?
What has to be changed in my code?
Thanks for your help!
|
|
|
|
|
|
Thanks for your help. It works fine now.
|
|
|
|
|
I feel quite defeated and overwhelmed at present. Apologies if this is done incorrectly. Any assistance would be warmly welcomed.
I'm writing a program in WPF, using c#, which should collect inputs via relevant textbox fields. These inputs should filter through to my sql command parameters, where I can then run the stored procedure. Then the info should populate back into a Datagrid in WPF mainwindow.
Basically, searching through historical stock pricing, returning all info between date, price, volume, etc, based on whichever values the user selects.
My SQL stored procedure returns expected values. The only way I can get my program to return the same values is to hardcode each input. I know I am missing the link between getting the values from each textbox into the SQL command parameters, but I'm at a loss as to how to do this. I think I need to set an event in my "mainwindow.xaml.cs" but I just cannot work out the right syntax...
<pre>namespace MBM3._0
{
public partial class MainWindow : Window
{
StockValues src = new StockValues();
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
this.DataContext = src;
}
public void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
textBoxStockSymbol.Text = "AEA";
textBoxDateFrom.Text = "2000-01-03";
textBoxDateTo.Text = "2010-02-08";
textBoxSPOpenFrom.Text = "0";
textBoxSPOpenTo.Text = "50";
textBoxSPCloseFrom.Text = "50";
textBoxSPCloseTo.Text = "50";
textBoxSPACloseFrom.Text = "50";
textBoxSPACTo.Text = "50";
textBoxSPHighFrom.Text = "50";
textBoxSPHighTo.Text = "50";
textBoxSPLowFrom.Text = "50";
textBoxSPLowTo.Text = "50";
textBoxSVolumeFrom.Text = "50";
textBoxSVolumeTo.Text = "50";
}
private void dataGrid_Loaded(object sender, RoutedEventArgs e)
{
}
private void buttonFind_Click(object sender, RoutedEventArgs e)
{
try
{
DataTable MSQ = DataLayer.Stock.MSQ("WPFDemo App");
dataGrid.ItemsSource = MSQ.DefaultView;
}
catch (SqlException sqlex)
{
MessageBox.Show("Error: " + sqlex.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void textBoxStockSymbol_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
And Stock Layer
<pre>namespace DataLayer
{
public class Stock
{
public static DataTable MSQ(string appName)
{
DataTable table1 = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter();
StockValues sv = new StockValues();
using (SqlConnection conn = Database.GetSqlConnection())
{
SqlCommand cmd = new SqlCommand("SELECT date, stock_symbol, stock_price_open, stock_price_close, stock_price_lo, stock_price_high, stock_price_adj_close, stock_volume FROM NYSE WHERE date BETWEEN @date_from AND @date_to AND stock_symbol LIKE @stock_symbol AND stock_price_open BETWEEN @stock_price_open_from AND @stock_price_open_to AND stock_price_close BETWEEN @stock_price_close_from AND @stock_price_adj_close_to AND stock_price_lo BETWEEN @stock_price_lo_from AND @stock_price_lo_to AND stock_price_high BETWEEN @stock_price_high_from AND @stock_price_high_to AND stock_price_adj_close BETWEEN @stock_price_adj_close_from AND @stock_price_adj_close_to AND stock_volume BETWEEN @stock_volume_from AND @stock_volume_to", conn);
cmd.Parameters.Add(new SqlParameter("date_from", System.Data.SqlDbType.Date));
cmd.Parameters.Add(new SqlParameter("date_to", System.Data.SqlDbType.Date));
cmd.Parameters.Add(new SqlParameter("stock_symbol", System.Data.SqlDbType.VarChar));
cmd.Parameters.Add(new SqlParameter("stock_price_open_from", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_open_to", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_close_from", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_close_to", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_lo_from", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_lo_to", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_high_from", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_high_to", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_adj_close_from", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_price_adj_close_to", System.Data.SqlDbType.Float));
cmd.Parameters.Add(new SqlParameter("stock_volume_from", System.Data.SqlDbType.Int));
cmd.Parameters.Add(new SqlParameter("stock_volume_to", System.Data.SqlDbType.Int));
cmd.Parameters["date_from"].Value = "2000-01-03";
cmd.Parameters["date_to"].Value = "2010-02-08";
cmd.Parameters["stock_symbol"].Value = "%";
cmd.Parameters["stock_price_open_from"].Value = "50";
cmd.Parameters["stock_price_open_to"].Value = "50";
cmd.Parameters["stock_price_close_from"].Value = "0";
cmd.Parameters["stock_price_close_to"].Value = "500";
cmd.Parameters["stock_price_lo_from"].Value = "0";
cmd.Parameters["stock_price_lo_to"].Value = "500";
cmd.Parameters["stock_price_high_from"].Value = "0";
cmd.Parameters["stock_price_high_to"].Value = "500";
cmd.Parameters["stock_price_adj_close_from"].Value = "0";
cmd.Parameters["stock_price_adj_close_to"].Value = "500";
cmd.Parameters["stock_volume_from"].Value = "0";
cmd.Parameters["stock_volume_to"].Value = "1000000000";
da1 = new SqlDataAdapter(cmd);
da1.Fill(table1);
}
return table1;
}
}
}
public class StockValues
{
public DateTime date_from { get; set; }
public DateTime date_to { get; set; }
public string stock_symbol { get; set; }
public float stock_price_open_from { get; set; }
public float stock_price_open_to { get; set; }
public float stock_price_close_from { get; set; }
public float stock_price_close_to { get; set; }
public float stock_price_lo_from { get; set; }
public float stock_price_lo_to { get; set; }
public float stock_price_high_from { get; set; }
public float stock_price_high_to { get; set; }
public float stock_price_adj_close_from { get; set; }
public float stock_price_adj_close_to { get; set; }
public int stock_volume_from { get; set; }
public int stock_volume_to { get; set; }
}
|
|
|
|
|
You'll need to modify your MSQ method to accept the parameters. It looks like your StockValues class is intended to hold the parameter values.
public static DataTable MSQ(StockValues sv)
{
using (SqlConnection conn = Database.GetSqlConnection())
using (SqlCommand cmd = new SqlCommand("SELECT date, stock_symbol, stock_price_open, stock_price_close, stock_price_lo, stock_price_high, stock_price_adj_close, stock_volume FROM NYSE WHERE date BETWEEN @date_from AND @date_to AND stock_symbol LIKE @stock_symbol AND stock_price_open BETWEEN @stock_price_open_from AND @stock_price_open_to AND stock_price_close BETWEEN @stock_price_close_from AND @stock_price_adj_close_to AND stock_price_lo BETWEEN @stock_price_lo_from AND @stock_price_lo_to AND stock_price_high BETWEEN @stock_price_high_from AND @stock_price_high_to AND stock_price_adj_close BETWEEN @stock_price_adj_close_from AND @stock_price_adj_close_to AND stock_volume BETWEEN @stock_volume_from AND @stock_volume_to", conn))
{
cmd.Parameters.AddWithValue("@date_from", sv.date_from);
cmd.Parameters.AddWithValue("@date_to", sv.date_to);
cmd.Parameters.AddWithValue("@stock_symbol", sv.stock_symbol);
cmd.Parameters.AddWithValue("@stock_price_open_from", sv.stock_price_open_from);
cmd.Parameters.AddWithValue("@stock_price_open_to", sv.stock_price_open_to);
cmd.Parameters.AddWithValue("@stock_price_close_from", sv.stock_price_close_from);
cmd.Parameters.AddWithValue("@stock_price_close_to", sv.stock_price_close_to);
cmd.Parameters.AddWithValue("@stock_price_lo_from", sv.stock_price_lo_from);
cmd.Parameters.AddWithValue("@stock_price_lo_to", sv.stock_price_lo_to);
cmd.Parameters.AddWithValue("@stock_price_high_from", sv.stock_price_high_from);
cmd.Parameters.AddWithValue("@stock_price_high_to", sv.stock_price_high_to);
cmd.Parameters.AddWithValue("@stock_price_adj_close_from", sv.stock_price_adj_close_from);
cmd.Parameters.AddWithValue("@stock_price_adj_close_to", sv.stock_price_adj_close_to);
cmd.Parameters.AddWithValue("@stock_volume_from", sv.stock_volume_from);
cmd.Parameters.AddWithValue("@stock_volume_to", sv.stock_volume_to);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
return table;
}
}
In your buttonFind_Click method, you'll need to create an instance of the StockValues class, populate it from the textbox values, and then pass it to the MSQ method.
private void buttonFind_Click(object sender, RoutedEventArgs e)
{
try
{
StockValues sv = new StockValues
{
stock_symbol = textBoxStockSymbol.Text
};
DateTime date;
if (DateTime.TryParse(textBoxDateFrom.Text, out date))
{
sv.sv.date_from = date;
}
if (DateTime.TryParse(textBoxDateTo.Text, out date))
{
sv.date_to = date;
}
float valueFloat;
if (float.TryParse(textBoxSPOpenFrom.Text, out valueFloat))
{
sv.stock_price_open_from = valueFloat;
}
if (float.TryParse(textBoxSPOpenTo.Text, out valueFloat))
{
sv.stock_price_open_to = valueFloat;
}
if (float.TryParse(textBoxSPCloseFrom.Text, out valueFloat))
{
sv.stock_price_close_from = valueFloat;
}
if (float.TryParse(textBoxSPCloseTo.Text, out valueFloat))
{
sv.stock_price_close_to = valueFloat;
}
if (float.TryParse(textBoxSPLowFrom.Text, out valueFloat))
{
sv.stock_price_lo_from = valueFloat;
}
if (float.TryParse(textBoxSPLowTo.Text, out valueFloat))
{
sv.stock_price_lo_to = valueFloat;
}
if (float.TryParse(textBoxSPHighFrom.Text, out valueFloat))
{
sv.stock_price_high_from = valueFloat;
}
if (float.TryParse(textBoxSPHighTo.Text, out valueFloat))
{
sv.stock_price_high_to = valueFloat;
}
if (float.TryParse(textBoxSPACloseFrom.Text, out valueFloat))
{
sv.stock_price_adj_close_from = valueFloat;
}
if (float.TryParse(textBoxSPACTo.Text, out valueFloat))
{
sv.stock_price_adj_close_to = valueFloat;
}
int valueInt;
if (int.TryParse(textBoxSVolumeFrom.Text, out valueInt))
{
sv.stock_volume_from = valueInt;
}
if (int.TryParse(textBoxSVolumeTo.Text, out valueInt))
{
sv.stock_volume_to = valueInt;
}
DataTable MSQ = DataLayer.Stock.MSQ(sv);
dataGrid.ItemsSource = MSQ.DefaultView;
}
catch (SqlException sqlex)
{
MessageBox.Show("Error: " + sqlex.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|