Mình mới học về C#, khi chạy thì bị lỗi như này <Fill: SelectCommand.Connection property has not been initialized.>
Các bạn chỉ rõ cụ thể cho mình với.
Đây là class functions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace test1
{
class Functions
{
public static SqlConnection Conn;
public static void Connect()
{
Conn = new SqlConnection();
Conn.ConnectionString = "Data Source=.\\SQLExpress;AttachDbFilename=C:\\Users\\Fat Nhi\\Documents\\Visual Studio 2010\\Projects\\test1\\test1\\Database\\test1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
try
{
Conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static DataTable GetDataToTable(string sql)
{
DataTable table = new DataTable();
SqlDataAdapter mydata = new SqlDataAdapter(sql, Conn);
mydata.Fill(table);
return table;
}
public static void Disconnect()
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
Conn.Dispose();
Conn = null;
}
}
}
Đây là form chính
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace test1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
btnLuu.Enabled = false;
btnBoqua.Enabled = false;
txtMahang.Enabled = false;
LoadDataGridView();
}
DataTable tbl;
private void LoadDataGridView()
{
string sql;
sql = "select * from tblHanghoa";
tbl = Functions.GetDataToTable(sql);
dgv.DataSource = tbl;
}
}