从datagridview中选中的复选框获取值c#

时间:2016-11-11 08:50:20

标签: c# checkbox datagridview datatable tableadapter

我在datagridview中检查复选框中的值时遇到问题。我希望获得复选框选中的所有ID,但我只获得了最新的检查。

这是我的代码:

string Id = "";

ds_utilityTableAdapters.tbl_membersTableAdapter tam = new ds_utilityTableAdapters.tbl_membersTableAdapter();    
ds_utility.tbl_membersDataTable dtm = new ds_utility.tbl_membersDataTable();

foreach (DataGridViewRow row in dgv_members.Rows)    
{        
    if (row.Cells[0].Value != null && (Boolean)row.Cells[0].Value == true)
    {
        Id= row.Cells[1].Value.ToString();

        // using Id to display data in crystal report viewer  
        // but only read the latest checkbox value

        dtm = tam.GetDataBy_SearchId(Id); 

        // in my dataset (ds_utility), I wrote the query like this
        // SELECT * FROM tbl_members WHERE (Id = ?)
    }
}

如何编写查询以获取所有值?

1 个答案:

答案 0 :(得分:1)

从我看到你有多种选择:

创建ds_utility.tbl_membersDataTable列表,并在每次迭代后将表添加到列表中。这是最简单的方法,但它会给你带来问题,因为你必须首先遍历多个表。它看起来像这样:

string Id = "";

ds_utilityTableAdapters.tbl_membersTableAdapter tam = new    ds_utilityTableAdapters.tbl_membersTableAdapter();       List<ds_utility.tbl_membersDataTable> dtm = new List<ds_utility.tbl_membersDataTable>();

foreach (DataGridViewRow row in dgv_members.Rows)     {         if (row.Cells[0].Value != null && (Boolean)row.Cells[0].Value == true) {
    Id= row.Cells[1].Value.ToString();

    // using Id to display data in crystal report viewer  
    // but only read the latest checkbox value

    dtm.Add(tam.GetDataBy_SearchId(Id));

    // in my dataset (ds_utility), I wrote the query like this
    // SELECT * FROM tbl_members WHERE (Id = ?) } } 

但在你的情况下,最好的选择是更改sql查询,而不是传递一个Id,传入Id的连接列表。您可以通过修改您的SQL来实现此目的:

SELECT * FROM tbl_members WHERE Id in (?)

将代码更改为:

string Id = "";

ds_utilityTableAdapters.tbl_membersTableAdapter tam = new ds_utilityTableAdapters.tbl_membersTableAdapter();    
ds_utility.tbl_membersDataTable dtm = new ds_utility.tbl_membersDataTable();
List<string> idList = new List<string>();

foreach (DataGridViewRow row in dgv_members.Rows)    
{        
    if (row.Cells[0].Value != null && (Boolean)row.Cells[0].Value == true)
    {
        Id= row.Cells[1].Value.ToString();

        // using Id to display data in crystal report viewer  
        // but only read the latest checkbox value

    idList.Add(Id);
    }
}

dtm = tam.GetDataBy_SearchId(string.Join(",", idList));