通过复选框从gridview获取值

时间:2013-03-13 02:39:32

标签: asp.net gridview

enter image description here

我有这个gridview,我试图打印出用户检查的任何列的MMBR_PROM_ID。

(Default.apsx)

Welcome to ASP.NET!

    </h2>

            <div style="width: 700px; height: 370px; overflow: auto; float: left;">
                <asp:GridView ID="GridView1" runat="server" HeaderStyle-CssClass="headerValue" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged">
                <Columns>
                <asp:TemplateField HeaderText="Generate">
                    <ItemTemplate>
                        <asp:CheckBox ID="grdViewCheck" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                </Columns>
                </asp:GridView>
                </div>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Generate" />

</asp:Content>  

(Default.aspx.cs)

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FrontOffEntities tmpdb = new FrontOffEntities();

            List<MMBR_PROM> newListMMBR_Prom = tmpdb.MMBR_PROM.ToList();


            GridView1.DataSource = newListMMBR_Prom;
            GridView1.DataBind();
        }

    }  

所以我的目标是当我按下生成时我希望能够以字符串的形式打印出用户检查的所有MMBR_PROM_ID。我有点新的aspnet所以我很难处理语法

1 个答案:

答案 0 :(得分:2)

根据您提到的要求,您可以尝试下面给出的代码,以便在生成按钮上的 Gridview1 中获取 MMBR_PROM_ID 的值。

     //For every row in the grid
     foreach (GridViewRow r in GridView1.Rows)
        {
            //Find the checkbox in the current row being pointed named as grdViewCheck
            CheckBox chk = (CheckBox)r.FindControl("grdViewCheck");

            //Print the value in the reponse for the cells[1] which is MMBR_PROM_ID
            if (chk!=null && chk.Checked)
            {
                Response.Write(r.Cells[1].Text);
            }
        }

此处,单元格[1]指的是特定行的单元格索引,在您的情况下是 MMBR_PROM_ID ,您要打印它。希望这有帮助!

如果您要查找逗号分隔值 MMBR_PROM_ID ,则下面提到的代码将适合您。

     //Declaration of string variable 
     string str="";

     //For every row in the grid
     foreach (GridViewRow r in GridView1.Rows)
        {
            //Find the checkbox in the current row being pointed named as grdViewCheck
            CheckBox chk = (CheckBox)r.FindControl("grdViewCheck");

            //Print the value in the reponse for the cells[1] which is MMBR_PROM_ID
            if (chk!=null && chk.Checked)
            {
                Response.Write(r.Cells[1].Text);
                //appending the text in the string variable with a comma
                str = str + r.Cells[1].Text + ", ";
            }
        }
      //Printing the comma seperated value for cells[1] which is MMBR_PROM_ID
      Response.Write(str);