با سلام خدمت همه دوستان
من مشکلمو با این روش حل کردم:
اول یه کلاس درست کردم و کانکشن رو توش تعریف کردم، به نام DataFunctions :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace MyApp
{
public class DataFunctions
{
SqlConnection scon;
public bool ConfigConnection()
{
string con_str = @"Data Source=.\SQLEXPRESS;" +
@"AttachDbFilename = " + Application.StartupPath +
@"\DataBase.mdf;" +
@"Integrated Security=True;" +
@"Connect Timeout=30;" +
@"User Instance=True";
scon = new SqlConnection(con_str);
try
{
open_connection();
close_connection();
return true;
}
catch (Exception e)
{
// show error message
}
}
public void open_connection()
{
if (scon.State != ConnectionState.Open )
{
scon.Open();
}
}
public void close_connection()
{
if (scon.State != ConnectionState.Closed)
{
scon.Close();
}
}
}
}
بعدش تو فرم اصلی تعریفش کردم، البته استاتیک :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyApp
{
public partial class frmMain : Form
{
public static DataFunctions df = new DataFunctions();
public frmMain()
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (!df.ConfigConnection())
{
// show message
// close application
}
}
}
}
حالا تو فرمای دیگه فقط open میکنم و بعد از استفاده close، اینجوری :
frmMain.df.open_connection()
اینجوری هم یه بار کانکشن تعریف کردم، هم همه جا در دسترسه