如何使用数据源填充datagridview [英] How to populate datagridview with datasource

查看:84
本文介绍了如何使用数据源填充datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个绑定到数据库表的datagridview。 dgv显示项目的数据,

其中项目可能是一切。

添加新项目时dgv的DataSource有0行,dgv只显示列(正确)。

将数据添加到项目中,我使用


I have a datagridview bound to a database-table. the dgv shows data of an item,
where the item could be everything.
when adding a new item the dgv's DataSource has 0 rows, the dgv just shows the columns (correctly).
to add data to the item, I use

Item_CellMouseDown

将项目ID

添加到新项目中行,因为id-column在dgv中不可见。



低于两个版本的方法,但没有一个正常工作。



代码A:

to add the items id
to the new row, because the id-column is not visible in dgv.

below a two versions of the method and none works correctly.

code A :

private void Item_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    int row = e.RowIndex;

    DataRow dr;
    if (row == SourceTable.Rows.Count) {
       dr = SourceTable.NewRow();
       SourceTable.Rows.Add(dr);

       dr["ID"] = this.ID;
    }
}



代码B:


code B :

private void Item_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    int row = e.RowIndex;

    object  id = Item["Id",row].Value;
    if (id == null || id.ToString() == string.Empty) {
       Item["Id",row].Value = this.ID;
    }
}





我尝试了什么: < br $>


代码A:项目显示三行,SourceTable有两行



代码B:项目显示一行,SourceTable有0行



但它应该是Item显示两行,SourceTable有1行



我错过了什么或者我在这里做错了什么?



提前谢谢

franz



What I have tried:

code A : Item shows three rows, SourceTable has two rows

code B : Item shows one row, SourceTable has 0 rows

however it should be Item shows two rows, SourceTable has 1 row

what am I missing or what am I doing wrong here ?

thanks in advance
franz

推荐答案

我只是不能在今年余下的时间里试图找出错误所以我已经添加了

I just can't spend the rest of this year trying to find out what's wrong so I've added
if (Item.Rows.Count > SourceTable.Rows.Count+1)
     Item.Rows.RemoveAt(1);



到if语句的末尾



这个正常工作!

(实际上只有在表空时才执行RemoveAt)


to the end of the if statement

with this it works correctly !
(actually the RemoveAt is only done when table was empty)


这篇关于如何使用数据源填充datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆