Привет. Имеется WPF Application. Помогите создать подключение к SQL Compact, извлечь из него информацию и вывести ее в окно WPF. Вот что я написал: | Код |
Window1.xaml.cs ============ namespace WpfApplication1 { public partial class Window1 : Window { public Window1() { InitializeComponent(); }
private void cmdGetProduct_Click(object sender, RoutedEventArgs e) { int ID; if (Int32.TryParse(txtID.Text, out ID)) { try { gridProductDetails.DataContext = App.StoreDB.GetProduct(ID); } catch { MessageBox.Show("Ошибка подключения к базе данных."); } } else { MessageBox.Show("Неверный ID."); } } } }
App.xaml.cs ======== namespace WpfApplication1 {
public partial class App : Application { private static StoreDB storeDB = new StoreDB(); public static StoreDB StoreDB { get { return storeDB; } } }
public class StoreDB { private string connectionString = "Data Source='Database1.sdf'";
public Product GetProduct(int ID) { //SqlCeEngine engine = new SqlCeEngine("Data Source=Database1.sdf"); //SqlCeConnection connection = new SqlCeConnection(engine.LocalConnectionString); SqlCeConnection connection = new SqlCeConnection(connectionString); //SqlCeCommand cmd = connection.CreateCommand("SELECT * FROM clienti ORDER BY nume"); SqlCeCommand cmd = new SqlCeCommand("GetProductByID", connection); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("ProductID", ID); try { connection.Open(); SqlCeDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow); if (reader.Read()) { Product product = new Product((string)reader["ModelNumber"], (string)reader["ModelName"], (decimal)reader["UnitCost"], (string)reader["Description"]); return(product); } else { return null; } } finally { connection.Close(); } } }
public class Product { private string modelNumber; public string ModelNumber { get { return modelNumber; } set { modelNumber = value; } } private string modelName; public string ModelName { get { return modelName; } set { modelName = value; } } private decimal unitCost; public decimal UnitCost { get { return unitCost; } set { unitCost = value; } } private string description; public string Description { get { return description; } set { description = value; } } public Product(string modelNumber, string modelName, decimal unitCost, string description) { ModelNumber = modelNumber; ModelName = modelName; UnitCost = unitCost; Description = description; } } }
|
Программа доходит только до MessageBox.Show("Ошибка подключения к базе данных.").
|