2013-03-13 69 views
2

enter image description here充分利用GridView控件的值與複選框

我有這個GridView和IM試圖打印出取其列由用戶選擇了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由用戶檢查。 IM還挺新ASPNET這樣一個困難時期IM應對了語法

回答

2

按照您提要求,你可以試試下面給出的代碼從Gridview1得到Generate按鈕點擊的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); 
+0

感謝它的工作。我怎麼能用逗號分開它?並把它放在生成按鈕? – Yinks 2013-03-13 05:04:18

+0

您是否在逗號分隔的字符串中查看所有選中的行MMBR_PROM_ID?如果是的話,那麼你需要在foreach上面聲明一個字符串變量,並且在if條件 – 2013-03-13 05:14:53

+0

內使用stringVar + = r.cells [1] .Text +「,」你能編輯上面的答案嗎?可以嗎? – Yinks 2013-03-13 05:34:01