2013-12-17 106 views
3

我得到了一個gridview,從數據庫中提取出一列「產品」。C#Gridview複選框字段VS(模板字段+複選框)

因此,我需要一個checkbox供用戶在完成時對gridview中的每個產品進行「檢查」。

我對複選框字段VS(模板字段+複選框)研究和決定使用(模板字段+複選框)gridview舉行checkbox

GridView的柱[0] =產品名稱 GridView的列[1] =複選框

「檢查」 一些checkboxes後,則用戶點擊提交將觸發以下事件。

string checkedBy;   
foreach (GridViewRow row in grvCheckList.Rows) 
{ 
    // Im not sure how to check if each checkbox has been "checked" 
    // or not as it is in the gridview cell. 

    // what I like to have is 
     if((checkbox in column[1]).checked == true) 
     { 
     checkedBy = // Staff name 
     // my codes to store the staff name into database with respective to the product listed in    the gridview row 
     } 
     else 
     { 
     checkedBy = "NULL" 
     // my code to store "NULL" into database with respect to the product listed in the gridview  row 
     } 
} 

對於平常checkbox,我通常做的是低於

if(checkbox1.checked == true) 
else if(checkbox2.checked == true) 
else if(checkbox3.checked == true) 
etc 

所以我的問題是,我該如何檢查,如果每一行的checkbox一直是「檢查」或沒有,儘管在每一行gridview使用相同的checkbox

回答

4

CheckBox字段:
必須綁定到數據庫字段並且是隻讀的。

模板字段中的複選框: 可以用作rocord選擇器。

樣品與模板字段:

ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1"> 
     <Columns> 
      <asp:TemplateField> 
       <ItemTemplate> 
        <asp:CheckBox ID="CheckBox1" runat="server" /> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" /> 
      <asp:BoundField DataField="fname" HeaderText="fname" SortExpression="fname" /> 
      <asp:BoundField DataField="lname" HeaderText="lname" SortExpression="lname" /> 
     </Columns> 
    </asp:GridView> 
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource> 
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> 

後面的代碼:

protected void Button1_Click(object sender, EventArgs e) 
    { 
     foreach (GridViewRow item in GridView1.Rows) 
     { 
      CheckBox chk = (CheckBox)item.FindControl("CheckBox1"); 
      if (chk != null) 
      { 
       if (chk.Checked) 
       { 
        // process selected record 
        Response.Write(item.Cells[1].Text + "<br>"); 
       } 
      } 
     } 
    }