【问题标题】:How do I get the value of specific cells on a gridview based on checkbox selections on the same row?如何根据同一行上的复选框选择获取网格视图上特定单元格的值?
【发布时间】:2013-06-13 17:06:28
【问题描述】:

我从 API 获取数据并将其放入数据表中:

DataTable showsTable = Transporter.GetDataTableFromAPI(callingURL);

gvShows.DataSource = showsTable;
gvShows.DataBind();

然后我在 dataBind 事件中向该表添加一个新列:

protected void gvShows_DataBound(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvShows.Rows)
            {
                var tcCheckCell = new TableCell();
                var chkCheckBox = new CheckBox();
                tcCheckCell.Controls.Add(chkCheckBox);
                row.Cells.AddAt(0, tcCheckCell);
            }
        }

单击按钮时,我想根据检查的行获取 3 个单元格值。

值是:

  • 数据源
  • showId
  • 剧集ID

我基本上想做...

对于每个选中的行,获取 dataSource、showId 和 episodeId 列的值并将其放入 3 个不同的变量中。

我不确定这是否正确或如何完成:

foreach (GridViewRow row in gvShows.Rows)
            {
                CheckBox chk = row.Cells[0].FindControl("chkCheckBox") as CheckBox;
                if (chk != null && chk.Checked)
                {
                    dataSource = ...
                    showId = ...
                    episodeId = ...
                }
            }

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:
    foreach (GridViewRow row in gvShows.Rows)
    {
        CheckBox chk = row.Cells[0].FindControl("chkCheckBox") as CheckBox;
        if (chk != null && chk.Checked)
        {
            //Access the data written in cell
            dataSource = row.Cells[1].Text; 
            //if you are using DataKeys in GridView, which I particularly like to do
            //(and it's useful for data you do not dsiplay), you 
            //can access data like this:
            showId = gvShows.DataKeys[row.RowIndex]["showId"].ToString()
        }
    }
    

    【讨论】:

    • 查找控件返回 NULL
    • @Rj。复选框不是第一列的情况吗?您可以随时尝试row.FindControl("chkCheckBox") 在整个行中进行搜索。另外,请确保您的复选框的 ID 实际上是“chkCheckBox”
    • 是的,它仍然返回为 NULL。该控件在运行时添加到gridview。我不确定这是否是问题所在。 (我的 OP 中的第二个代码块)
    • @Rj。是的,这就是问题所在,因为您没有为控件分配 ID(变量的名称不是控件的 ID)。尝试在设计时添加复选框,但使其不可见。将其设置在您的 gvShows_DataBound 中可见
    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 2023-03-17
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2015-01-29
    • 2023-03-13
    相关资源
    最近更新 更多