我设置一个List有2个元素到dataGridView的DataSource,但它总是有一行,RowCount属性是1.这太奇怪了
我的代码下面有一些实体类名称,我必须解释。
HoaDon is Order
ChiTietHoaDon is OrderDetail
SanPham is Product
代码:
using GymFitnessOlympic.Controller;
using GymFitnessOlympic.Models;
using GymFitnessOlympic.Models.Util;
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;
namespace GymFitnessOlympic.View.ActForm
{
public partial class FrmBanHang2 : Form
{
List<SanPham> allSanPham;
List<ChiTietHoaDon> allChiTiet = new List<ChiTietHoaDon>();
HoaDon hoaDon = new HoaDon();
public FrmBanHang2()
{
InitializeComponent();
int phongID = Login.GetPhongHienTai().MaPhongTap;
allSanPham = SanPhamController.GetList(phongID);
dgrChiTiet.AutoGenerateColumns = false;
dgrChiTiet.AutoGenerateColumns = false;
loadListSanPham(allSanPham);
}
void loadListSanPham(List<SanPham> li)
{
lbSanPham.DataSource = li;
}
void updateTable()
{
dgrChiTiet.DataSource = allChiTiet;
int n = dgrChiTiet.RowCount;
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (spnQuantity.Value <= 0)
{
dxErrorProvider1.SetError(spnQuantity, "Quantity must be greater than 0");
spnQuantity.Focus();
return;
}
int gia;
if (!int.TryParse(txtPrice.Text, out gia) || (gia % 500 != 0) || gia <= 0)
{
txtPrice.Focus();
dxErrorProvider1.SetError(txtPrice, "Invalid Price");
return;
}
if (lbSanPham.SelectedItem != null)
{
var sp = (SanPham)lbSanPham.SelectedItem;
int soLuong = int.Parse(spnQuantity.Text);
ChiTietHoaDon c = new ChiTietHoaDon()
{
Gia = gia,
MaSanPham = sp.MaSanPham,
SoLuong = soLuong,
SanPham = sp
};
var old = allChiTiet.FirstOrDefault(c1 => c1.MaSanPham == c.MaSanPham);
if (old != null)
{
old.SoLuong += c.SoLuong;
}
else
{
allChiTiet.Add(c);
}
}
updateTable();
}
private void lbSanPham_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbSanPham.SelectedItem != null)
{
var sp = (SanPham)lbSanPham.SelectedItem;
txtTenSanPham.Text
= sp.TenSanPham;
txtPrice.Text = sp.Gia.ToString();
spnQuantity.Text = "1";
}
}
}
}
答案 0 :(得分:4)
这是因为您使用List<ChiTietHoaDon>
作为datagridview的数据源,并且它不会通知更改,因此网格不会显示新项目。
您应该使用BindingList<ChiTietHoaDon>
代替。
但是,如果您想继续使用List<ChiTietHoaDon>
,要更新网格,您可以先设置dgrChiTiet.DataSource=null;
,然后设置dgrChiTiet.DataSource = allChiTiet;