Báo lỗi: " object reference not set to an instance of an object" khi lưu vào csdl trong lap trinh visual 2005?
Mình làm bài tập win bi bao lỗi như vây mà không biết làm sao. khi mình nhấn vào button lưu thì bị báo lỗi như vậy. minh gặp rất nhiều bài như vậy mà không biết giải quyết sao nưa. code của mình là
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace QL_Nhan_Su_Huong_Tuyet
{
public partial class frm_QUAN_LY_KI_LUAT_NV : Form
{
public frm_QUAN_LY_KI_LUAT_NV()
{
InitializeComponent();
}
cls_QL_Nhan_Su obj = new cls_QL_Nhan_Su();
DataSet ds;
private void QUAN_LY_KI_LUAT_NV_Load(object sender, EventArgs e)
{
ds = new DataSet();
ds = obj.TT_KT();
dgliluat.DataSource = ds.Tables["tbl_KHEN_THUONG"];
hienthi();
}
public void hienthi()
{
ds = new DataSet();
ds = obj.hienthi_ma_NV();
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "MA_NV";
comboBox1.ValueMember = "HO_TEN_NV";
}
private void gandl(DataSet ds)
{
if (txtma.Text == "")
{
MessageBox.Show("Bạn hãy điền đầy đủ thông tin", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
DataRow drw;
drw = ds.Tables["tbl_KHEN_THUONG"].NewRow();
drw["MA_KT"] = txtma.Text;
drw["MA_NV"] = comboBox1.Text;
drw["LY_DO_KT"] = txthinhthuc.Text;
drw["NGAY_KT"] = txtngay.Text;
drw["SO_TIEN_KT"] = txtsotien.Text;
drw["GHI_CHU"] = txtghichu.Text;
ds.Tables["tbl_KHEN_THUONG"].Rows.Add(dr…
}
}
private void btnluu_Click(object sender, EventArgs e)
{
try
{
if (KiemTraTrungKhoa(ds, txtma.Text))
{
MessageBox.Show("Trùng Khóa", "Loi");
}
else
{
gandl(ds);
if (ds.HasChanges())
{
obj.Them(ds, "tbl_KHEN_THUONG");
ds.AcceptChanges();
MessageBox.Show("Cập nhật thành công", " Thông Báo");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Boolean KiemTraTrungKhoa(DataSet ds, string ma)
{
DataTable tbl = new DataTable();
tbl = ds.Tables["tbl_KHEN_THUONG"];
foreach (DataRow dr in tbl.Rows)
{
if (dr["MA_KT"].ToString().Equals(ma))
return true;
}
return false;
}
}
}
cũng viet code như vây nhưng mình làm trên form khác thi khong lam sao. mh làm y như vay sang form nay thi ko báo lối nhưng khi chọn vào nut lưu thì lại có vấn đề. ko luu dc. ai biết giúp mình với. minh am on nhe!
Có một đối tượng bạn sử dụng chưa được khởi tạo giá trị (mới chỉ khai báo), nên khi truy cập sẽ bị lỗi như vậy đó.
Bạn xem đó là biến nào rùi gán giá trị cho nó.
Chúc thành công!