我是DataGridView的新手,我正在尝试使用List作为数据源。
使用我当前的代码,我的网格显示3行,其中包含空数据。有人可以告诉我这有什么不对。
这是我的代码:
项目
class Item
{
public int id;
public string name;
public string imagePath;
public int type;
public int hp;
public int mp;
public int str;
public int dex;
public int vit;
public int agi;
public int iInt;
public int mnd;
public int att;
public int acc;
public int def;
public int eva;
public int matt;
public int macc;
public string text;
public Item()
{
}
public Item(int Id, string Name, string ImagePath, int STR, int DEX, int VIT, int AGI, int INT, int MND,
int ATT, int ACC, int DEF, int EVA, int MATT, int MACC, int HP, int MP, int Type, string Text)
{
id = Id;
name = Name;
imagePath = ImagePath;
type = Type;
str = STR;
dex = DEX;
vit = VIT;
agi = AGI;
iInt = INT;
mnd = MND;
att = ATT;
acc = ACC;
def = DEF;
eva = EVA;
matt = MATT;
macc = MACC;
text = Text;
}
这是我的表单代码:
datagridItems.Rows.Clear();
List<Item> items = new List<Item>();
Connection connection = new Connection();
string requeteItems = "SELECT * FROM Items";
connection.Open();
SqlDataReader myReader = connection.Read(requeteItems);
while (myReader.Read())
{
Item item = new Item();
item.id = int.Parse(myReader["Id"].ToString());
item.name = myReader["Name"].ToString();
item.imagePath = myReader["Image"].ToString();
item.hp = int.Parse(myReader["HP"].ToString());
item.mp = int.Parse(myReader["MP"].ToString());
item.str = int.Parse(myReader["STR"].ToString());
item.dex = int.Parse(myReader["DEX"].ToString());
item.vit = int.Parse(myReader["VIT"].ToString());
item.agi = int.Parse(myReader["AGI"].ToString());
item.iInt = int.Parse(myReader["INT"].ToString());
item.mnd = int.Parse(myReader["MND"].ToString());
item.att = int.Parse(myReader["ATT"].ToString());
item.acc = int.Parse(myReader["ACC"].ToString());
item.def = int.Parse(myReader["DEF"].ToString());
item.eva = int.Parse(myReader["EVAS"].ToString());
item.matt = int.Parse(myReader["MATT"].ToString());
item.macc = int.Parse(myReader["MACC"].ToString());
item.text = myReader["Text"].ToString();
item.type = 0;
items.Add(item);
}
connection.Close();
bsItems.DataSource = items;
}
连接返回数据没有问题。我想知道为什么我的线条有空白数据。
答案 0 :(得分:0)
试试这个,
var bindingList = new BindingList<Item>(items);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
答案 1 :(得分:0)
<强>参见:强>
How to bind list to dataGridView?
Binding List<T> to DataGridView in WinForm
使用BindingList并设置列的DataPropertyName - 属性。
示例:
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
更具约束力的相关信息..
Binding Controls to Data Created at Runtime
假设您有一个表示数据记录的对象,并且这些记录的列表应该显示在数据感知控件中。要允许此列表绑定到控件,您可以执行以下操作之一:
首先将字段转换为属性声明,然后使用BindingList启用控件的完整功能。
<强>参考文献:强>
grid control - how to bind grid datasource to List ?
Bind DataGrid to Generic List<> will not allow Add, Edit items in Grid
Problem with data binding to DevExpress XtraGrid