Download Here: SourceCode
using System.Data.SqlClient;
namespace dataBaseConnectionTutorial
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
SqlConnection connectToDataBase = null;
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|Datadirectory|\testDataBase.mdf;Integrated Security=True;User Instance=True";
private void button1_Click(object sender, RoutedEventArgs e)
{
if (connectToDatabase())
{
MessageBox.Show("Connection Established");
}
else
{
MessageBox.Show("Connection couldn't be Established");
}
}
public bool connectToDatabase()
{
bool connectionStatus = false;
connectToDataBase = new SqlConnection(connectionString);
try
{
connectToDataBase.Open();
connectionStatus = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connectionStatus = false;
}
return connectionStatus;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if (connectToDataBase == null)
{
MessageBox.Show("Please Connect to Database");
}
else
{
string query = "Select * from testTable";
SqlCommand queryToDataBase = new SqlCommand(query, connectToDataBase);
SqlDataReader dataReader = queryToDataBase.ExecuteReader();
while (dataReader.Read())
{
tableData.Items.Add(dataReader[1].ToString());
}
connectToDataBase.Close();
}
}
}
}
using System.Data.SqlClient;
namespace dataBaseConnectionTutorial
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
SqlConnection connectToDataBase = null;
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|Datadirectory|\testDataBase.mdf;Integrated Security=True;User Instance=True";
private void button1_Click(object sender, RoutedEventArgs e)
{
if (connectToDatabase())
{
MessageBox.Show("Connection Established");
}
else
{
MessageBox.Show("Connection couldn't be Established");
}
}
public bool connectToDatabase()
{
bool connectionStatus = false;
connectToDataBase = new SqlConnection(connectionString);
try
{
connectToDataBase.Open();
connectionStatus = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connectionStatus = false;
}
return connectionStatus;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if (connectToDataBase == null)
{
MessageBox.Show("Please Connect to Database");
}
else
{
string query = "Select * from testTable";
SqlCommand queryToDataBase = new SqlCommand(query, connectToDataBase);
SqlDataReader dataReader = queryToDataBase.ExecuteReader();
while (dataReader.Read())
{
tableData.Items.Add(dataReader[1].ToString());
}
connectToDataBase.Close();
}
}
}
}
No comments:
Post a Comment