在数据库ASP.NET C#中的gridview中选中了复选框

时间:2016-04-29 04:23:25

标签: c# asp.net gridview checkbox

我能够从数据库中检索出数据,以使用gridview中的复选框显示哪个是Y和N.但是现在我想能够存储在编辑后将哪个复选框重新检入数据库。

到目前为止我做了什么:

的.aspx

    <asp:GridView ID="SiteGridView" runat="server" CssClass="datagrid" 
                  GridLines="Vertical" AutoGenerateColumns="False"
                  Width="100%" 
                  AllowPaging="True" AllowSorting="True" 
                  DataKeyNames="promoID"  OnRowCommand="GvPage_RowCommand" 
                  OnPageIndexChanging="GvPage_PageIndexChanging" 
                  OnSorting="GvPage_Sorting" 
                  OnRowDatabound="SiteGridView_RowDataBound"
                  OnRowEditing="SiteGridView_RowEditing">
      <Columns>       
        <asp:TemplateField HeaderText="Default">
          <ItemTemplate>
            <asp:CheckBox ID="process_flag" runat="server" 
              Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
              Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>' />
          </ItemTemplate>
          <ItemStyle Width="20%" />
        </asp:TemplateField>
       </Columns>
     </asp:GridView>

代码隐藏:

     SqlCommand cmd = new SqlCommand("SELECT * , CAST(CASE defaults WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED FROM Promotions"); 
                SqlDataAdapter da = new SqlDataAdapter(); 
                DataTable dt = new DataTable(); 
                da.SelectCommand = cmd; 

                // Save results of select statement into a datatable 
                da.Fill(dt);

                SiteGridView.DataSource = dt;
                SiteGridView.DataBind(); 

        protected void SiteGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //check userrole & display accrodingly
                if (Session["ROLE"].ToString() != "SA")
                {
                    //ImageButton btnEdit = (ImageButton)e.Row.FindControl("btnDelete");
                    //btnEdit.Visible = false;
                    SiteGridView.Columns[4].Visible = false;
                }
            }
        }

3 个答案:

答案 0 :(得分:1)

你试过了吗? 已选中=&#39;&lt;%#Eval(&#34;已处理&#34;)%&gt;&#39;

如果是,您收到了哪些错误消息?

答案 1 :(得分:0)

首先使用foreach循环来查找检查哪些行。然后将这些行的ID存储在List中。

foreach (GridViewRow row in SiteGridView.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkRow = (row.Cells[0].FindControl("process_flag") as CheckBox);
                if (chkRow.Checked)
                {
                    string ID = row.Cells[columnID].Text;

答案 2 :(得分:0)

由于某种原因,复选框不会触发GridView RowCommand事件。可能可以通过适当调用ClientScript.GetPostBackEventReference()完成,但这是另一个复杂程度。因此,为了对CheckBox采取行动,请单击并单独处理事件:

(注意:我已经删除了大部分编码以澄清我的观点。)

  1. 在CheckBox集AutoPostBack="true"
  2. OnCheckedChanged添加处理程序。
  3. 确保DataKey包含您需要使用CheckBox状态更新的行的pk

    // Simplified version of your markup
    <asp:GridView ID="SiteGridView" runat="server" 
                  DataKeyNames="promoID" 
                  OnRowDataBound="SiteGridView_RowDataBound">
      <Columns>
        <asp:TemplateField HeaderText="Default">
          <ItemTemplate>
            <asp:CheckBox ID="process_flag" runat="server" 
              Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
              Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>'
              OnCheckedChanged="process_flag_CheckedChanged" />
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
    
  4. RowDataBound事件中,找到CheckBox并将行索引添加为属性

    // Merge this with your `RowDataBound` event
    protected void SiteGridView_RowDataBound( object sender, GridViewRowEventArgs e ) {
        if ( e.Row.RowType == DataControlRowType.DataRow ) {
            CheckBox cbx = ( CheckBox ) e.Row.FindControl( "CheckBox1" );
            cbx.Attributes[ "data-row-idx" ] = e.Row.RowIndex.ToString();
        }
    }
    
  5. 处理CheckChanged事件:

    // Add this handler to your code
    protected void process_flag_CheckedChanged( object sender, EventArgs e ) 
    {
        CheckBox cbx = ( CheckBox ) sender;
        Int32 rowidx = Convert.ToInt32(cbx.Attributes["data-row-idx"]);
        Int32 pk = (Int32) GridView4.DataKeys[rowidx].Value;
    
        // simple way to see event arguments before actually touching the database
        GridView4.Caption = string.Format(
            "CheckChanged: Row {0}, State: {1}, RowPK: {2} ", rowidx , (cbx.Checked ? "Checked" : "Unchecked"), pk );
    
        // Save Data and rebind the gridview to reflect changes
        // Verify your parameters before attempting an actual update
        // YourDatabaseCallWithAppropriateParamaters( ... );
        GridView1.DataBind();
    }