0

我有以下数据库设计:

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

我有一个 GridView,我用它来添加、删除和更新/编辑员工信息。此信息是员工用户名、姓名、徽章编号、职位名称、IsActive 和部门快捷方式。IsActive 是一个标志,它指示员工是否有空或在分配中。我将其设置为复选框,该列应显示两个值;活跃和不活跃。在编辑模式下,将显示复选框。如果选中,则表示该员工可用,否则表示不活动。

我编写了代码,一切正常,但现在我面临两个问题,我不知道如何让它们与我的代码一起工作。

  1. GridView 显示 True 或 False 而不是 Active 和 Inactive,我不知道为什么。
  2. 在编辑模式下,复选框将被显示,并且值(活动或非活动)将显示在旁边,不应显示。我只想显示复选框。

那么如何修改它们呢?

在此处输入图像描述

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;

        }
    }

我收到以下错误,我不知道为什么: 在此处输入图像描述

4

2 回答 2

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. 为了证明我的代码有效,我创建了一个带有单列的 gridview

<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.
于 2012-07-15T07:05:38.410 回答
0
  1. 它返回“true”或“false”,因为它期望来自 IsActive 的布尔数据类型。如果您想更改输出,我怀疑您需要根据网格的 ItemDataBound 事件有条件地修改它。
于 2012-07-15T07:06:59.297 回答