Hello Dear, I am new into the word of C#. I am trying to design a windows form application that have to do with a SDF database. I want an SQL statement that will fetch data from the related tables and display them in the labels on the form.
thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amira BedhiafiRank #601 · 4K reputationPosted Mar 3, 2025, 8:39 AM EST
First, you need to create the database and tables with the necessary relationships. For example, let's assume you have two tables: Customers and Orders.
CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, Name NVARCHAR(100) NOT NULL ); CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT, OrderDate DATETIME, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );Insert some sample data into the tables:
INSERT INTO Customers (CustomerID, Name) VALUES (1, 'John Doe'); INSERT INTO Customers (CustomerID, Name) VALUES (2, 'Jane Smith'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (101, 1, '2023-10-01'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (102, 2, '2023-10-02');In your Windows Forms application, you need to connect to the SDF database using the SqlCeConnection class.
using System; using System.Data.SqlServerCe; using System.Windows.Forms; public partial class Form1 : Form { private string connectionString = @"Data Source=your_database.sdf;"; public Form1() { InitializeComponent(); LoadData(); } private void LoadData() { using (SqlCeConnection connection = new SqlCeConnection(connectionString)) { connection.Open(); string query = @" SELECT Customers.Name, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Customers.CustomerID = @CustomerID"; using (SqlCeCommand command = new SqlCeCommand(query, connection)) { command.Parameters.AddWithValue("@CustomerID", 1); // Example CustomerID using (SqlCeDataReader reader = command.ExecuteReader()) { if (reader.Read()) { lblCustomerName.Text = reader["Name"].ToString(); lblOrderID.Text = reader["OrderID"].ToString(); lblOrderDate.Text = reader["OrderDate"].ToString(); } } } } } }In your Windows Forms designer, add labels to display the data:
- lblCustomerName
- lblOrderID
- lblOrderDate
When you run the application, it will fetch the data from the related tables (Customers and Orders) and display it in the labels on the form.