如何根据同一行上的复选框选择获取gridview上特定单元格的值?

时间:2013-06-13 17:06:29

标签: c# asp.net gridview

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

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);
            }
        }

单击按钮,我想根据CHECKED行获取3个单元格值。

值为:

  • 数据源
  • showId
  • episodeId

我基本上想做...

对于每个选中的行,请获取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 = ...
                }
            }

1 个答案:

答案 0 :(得分: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()
    }
}