从datagridviewc#中的复选框中获取值

本文关键字:获取 复选框 datagridviewc# | 更新日期: 2023-09-27 18:17:38

我有关于从datagridview选中的复选框中获取值的问题。我想获得复选框选中的所有Id,但我只获得了最近选中的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 = ?)
    }
}

如何写一个查询得到所有的值?

从datagridviewc#中的复选框中获取值

我看到你有多个选择:

创建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));