如何在GridView中修改此复选框?

时间:2012-07-15 06:52:31

标签: c# asp.net checkbox

我有以下数据库设计:

Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
Divisions Table: SapCode, DivisionShortcut

我有一个GridView,我用它来添加,删除和更新/编辑员工信息。此信息是员工用户名,名称,BadgeNo,JobTitle,IsActive和DivisionShortcut。 IsActive是一个标志,指示员工是否可用或在作业中 。我把它作为一个复选框,列应该显示两个值;主动和非主动。在编辑模式下,将显示复选框。如果选中它,则表示员工可以使用,否则表示处于非活动状态。

我编写了代码,一切正常,但现在我遇到了两个问题,我不知道如何使用我的代码。

  1. GridView显示True或False,而不是Active和Inactive 我不知道为什么。
  2. 在编辑模式下,将显示复选框,除此之外将显示值(活动或非活动),不应显示。我只想要显示复选框。
  3. 那么如何修改它们呢?

    enter image description here

    ASP.NET代码:

    <%-- GridView for User Management Subsystem --%>
            <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
                AutoGenerateColumns="False" DataKeyNames="Username" 
                DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84" 
                 CellPadding="3" CellSpacing="2" BorderStyle="None" 
                 BorderColor="#DEBA84">
                <FooterStyle ForeColor="#8C4510" 
                  BackColor="#F7DFB5"></FooterStyle>
                <PagerStyle ForeColor="#8C4510" 
                  HorizontalAlign="Center"></PagerStyle>
                <HeaderStyle ForeColor="White" Font-Bold="True" 
                  BackColor="#A55129"></HeaderStyle>
                <Columns>
                    <asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
                                    EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png" 
                                    CancelImageUrl="Images/icons/cancel324.png" />
    
                    <asp:TemplateField HeaderText="Division">
                        <ItemTemplate>
                            <%# Eval("DivisionShortcut")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
                                              DataTextField="DivisionShortcut" DataValueField="SapCode"
                                              SelectedValue='<%# Bind("DivisionCode")%>'>
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True" 
                        SortExpression="Username" />
    
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <%# Eval("Name")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Job Title">
                        <ItemTemplate>
                            <%# Eval("JobTitle")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Badge No.">
                        <ItemTemplate>
                            <%# Eval("BadgeNo")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Is Active?">
                        <ItemTemplate>
                            <%# Eval("IsActive")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="isActive" runat="server" 
                                          AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
                                          Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
                                          Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Delete?">
                        <ItemTemplate>
                            <span onclick="return confirm('Are you sure to Delete the record?')">
                                <asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
                            </span>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    

    代码隐藏:

    //for updating the (IsActive) column using checkbox inside the GridView
        protected void isActive_OnCheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkStatus = (CheckBox)sender;
            GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;
    
            //Get the ID which is the NetworkID of the employee
            string username = gvrow.Cells[2].Text;
            bool status = chkStatus.Checked;
    
            string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);
    
            string updateIsActive = "UPDATE Employee SET IsActive = @IsActive WHERE Username = @Username";
    
            SqlCommand cmd = new SqlCommand(updateIsActive, conn);
    
            cmd.Parameters.AddWithValue("@IsActive", status);
            cmd.Parameters.AddWithValue("@Username", username);
    
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (SqlException se)
            {
                throw se;
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
    

    更新

    我将代码更新如下: ASP.NET代码:

    <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
                AutoGenerateColumns="False" DataKeyNames="Username" 
                DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" BorderWidth="1px" BackColor="#DEBA84" 
                 CellPadding="3" CellSpacing="2" BorderStyle="None" 
                 BorderColor="#DEBA84">
                <FooterStyle ForeColor="#8C4510" 
                  BackColor="#F7DFB5"></FooterStyle>
                <PagerStyle ForeColor="#8C4510" 
                  HorizontalAlign="Center"></PagerStyle>
                <HeaderStyle ForeColor="White" Font-Bold="True" 
                  BackColor="#A55129"></HeaderStyle>
                <Columns>
                    <asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
                                    EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png" 
                                    CancelImageUrl="Images/icons/cancel324.png" />
    
                    <asp:TemplateField HeaderText="Division">
                        <ItemTemplate>
                            <%# Eval("DivisionShortcut")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
                                              DataTextField="DivisionShortcut" DataValueField="SapCode"
                                              SelectedValue='<%# Bind("DivisionCode")%>'>
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True" 
                        SortExpression="Username" />
    
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <%# Eval("Name")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Job Title">
                        <ItemTemplate>
                            <%# Eval("JobTitle")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Badge No.">
                        <ItemTemplate>
                            <%# Eval("BadgeNo")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Is Active?">
                        <ItemTemplate>
                            <asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive")%>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="isActive" runat="server" 
                                          AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
                                          Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
                                          Text='<%# Eval("IsActive")%>'/>
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Delete?">
                        <ItemTemplate>
                            <span onclick="return confirm('Are you sure to Delete the record?')">
                                <asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
                            </span>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    

    代码隐藏:

    //For showing Active or Inactive in the IsActive column instead of True or False
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Here we will select the IsActive column and modify its text
                Label isActive = new Label();
                isActive = (Label)e.Row.FindControl("lblIsActive");
                //Now, after getting the reference, we can set its text
                isActive.Text = "Active or Inactive";
    
                // First check Checkedbox is check or not, if not make it grey
                //if (e.Row.Cells[6].Text == "False")
                //    GridView1.BackColor = Color.Gray;
    
            }
        }
    

    我收到以下错误,我不知道原因: enter image description here

2 个答案:

答案 0 :(得分:2)

问题编号:1 您必须在网格视图中添加Row_DataBound事件,在其中选择IsActive列并将其文本替换为Active和InActive。但在进入代码之前对aspx代码进行一些改动:在你的项目模板而不是直接绑定中放置一个标签控件并将其绑定,就像我在下面的代码中所做的那样:

<asp:TemplateField HeaderText="Is Active?">
                <ItemTemplate>
                      <asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive") %>' ></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:CheckBox ID="isActive" runat="server" 
                                  AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
                                  Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
                                  Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
                </EditItemTemplate>
            </asp:TemplateField>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // here you will select the IsActive column and modify it's text
        Label isActive=new Label();
        isActive = (Label) e.row.FindControl("lblIsActive");
        // after getting the reference set its text
        isActive.Text="Active or InActive";            

    }
}

问题2: 从此

中删除条件
Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'

并将其替换为

 Eval("IsActive")

现在将显示复选框。

更新答案: You are receiving an object reference not found error, Please debug your site and check it why you are unable to get the exact reference. I saw you code and it looks that your code is fine. 为了证明我的代码有效,我创建了一个带有单列的网格视图

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                     <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                </ItemTemplate>                   
            </asp:TemplateField>
        </Columns>            
    </asp:GridView>
    // and bind this grid view in the Page_Load of my Page
    protected void Page_Load(object sender, EventArgs e)
    { 
    DataTable dt = new DataTable();
    dt.Columns.Add("name");

    DataRow row = dt.NewRow();
    row[0] = "Waqar Janjua";
    dt.Rows.Add(row);

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

    // When I view this page in the browser it shows "Waqar Janjua"
    // Now to update the columns text, I add the following code and it works.
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowState != DataControlRowState.Edit)
      {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        Label l = new Label();
        l = (Label)e.Row.FindControl("Label1");
        l.Text = "waqar";           
       }
      }
    }

   // When I run this page now, it shows me "Waqar" not "Waqar Janjua" The code works for me.

答案 1 :(得分:0)

  1. 它返回“true”或“false”,因为它期望来自IsActive的布尔数据类型。如果你想改变那个输出,我怀疑你需要在网格的ItemDataBound事件上有条件地修改它。