简体   繁体   中英

Gridview Cell Color needs to change based on CheckBox checked in asp.net/c# keep getting errors

I have a Gridview (ASP.NET / C#) that currently changes color based on dates provided by the user. Past Due is Red, Future or Current Date is white (Which Works Nicely.). I have also provided a checkbox in the gridview cell that designates "Complete", If that checkbox is checked. i want it to override and dates and change the cell color to Black, So far the errors i keep getting are either, object not set to an instance of an object when i have tried it under "RowDataBound" or now with the current code. i have tried putting it under "OnCheckedChanged" which now has prevented any changes to the checkbox.
The data is stored in the database as Bit. Update Command sets parameters as Boolean.

Any ideas on how to get this to work?

ASP.NET markup:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
     GridView1_RowUpdating="true" DataKeyNames="ID" OnRowUpdating="Page_Load"
     BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid"
     BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black"
     OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Verify Info Prod & Maturity Level" SortExpression="IPMaturity">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("IPMaturity", "{0:MM/dd/yyyy}") %>' Width="75"></asp:TextBox>
                <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" Text="Complete" Enabled="false" OnCheckedChanged="CheckBox1_CheckedChanged" 
                     Checked='<%# Bind ("CheckBox1") %>'></asp:CheckBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblIPMat" runat="server" Text='<%# Eval("IPMaturity", "{0:MM/dd/yyyy}") %>' Width="75"></asp:Label>
            </ItemTemplate>
            <HeaderStyle CssClass="verticaltext" Height="140px" Width="88px" HorizontalAlign="Center" VerticalAlign="Bottom" />
        </asp:TemplateField>

C# code behind:

protected void CheckBox1_CheckedChanged(object sender, EventArgs e) //from checkbox
{
     CheckBox chkItem = null;
     //Boolean chkb = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "CheckBox1"));

     foreach (GridViewRow grRow in GridView1.Rows)
     {
         if (grRow.RowType == DataControlRowType.DataRow)
         {
             chkItem = (CheckBox)grRow.Cells[4].FindControl("CheckBox1");
             bool bl = chkItem.Checked;

             if (bl == true)
             {
                 grRow.BackColor = Color.Black;
             }
         }
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)  // Changes color of cell based on date
    {
        string ipMaturity = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "IPMaturity"));
        DateTime? date1 = !string.IsNullOrEmpty(ipMaturity) ? Convert.ToDateTime(ipMaturity) : (DateTime?)null;

        if (date1.HasValue && date1 >= DateTime.Now)
            e.Row.Cells[4].BackColor = System.Drawing.Color.White;

        if (date1.HasValue && date1 < DateTime.Now)
            e.Row.Cells[4].BackColor = System.Drawing.Color.Red;
    }
}

Keeping as much of your code as possible, I've made a bare minimum example to show checkbox changing background color.

Things to point out, the code example above does not have Cells[4] (so I've just gone with 0). I've replaces SQL call with class ( IPMaturityData ) & hardcoded data. There is no call to enable EditItemTemplate , so I've just went ahead and added <asp:CommandField ShowEditButton="True" />

The code won't give you everything you need. However it should be enough to play around and get it working as desired.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    GridView1_RowUpdating="true" DataKeyNames="ID" OnRowUpdating="Page_Load"
    BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid"
    BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black"
    OnRowEditing="GridView1_RowEditing"
    OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("IPMaturity", "{0:MM/dd/yyyy}") %>' Width="75"></asp:TextBox>
                <asp:CheckBox ID="CheckBox1" 
                    runat="server" 
                    AutoPostBack="true"
                    Text="Complete"
                    OnCheckedChanged="CheckBox1_CheckedChanged" 
                    Checked='<%# Bind ("CheckBox1") %>'></asp:CheckBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblIPMat" runat="server" Text='<%# Eval("IPMaturity", "{0:MM/dd/yyyy}") %>' Width="75"></asp:Label>

            </ItemTemplate>
            <HeaderStyle CssClass="verticaltext" Height="140px" Width="88px" HorizontalAlign="Center" VerticalAlign="Bottom" />
        </asp:TemplateField>
        <asp:CommandField ShowEditButton="True" />
    </Columns>
</asp:GridView>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        this.DataBindGrid();
    }
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView grid = sender as GridView;

    if (grid == null)
    {
        return;
    }

    grid.EditIndex = e.NewEditIndex;
    this.DataBindGrid();
}
  
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)  // Changes color of cell based on date
    {
        string ipMaturity = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "IPMaturity"));
        DateTime? date1 = !string.IsNullOrEmpty(ipMaturity) ? Convert.ToDateTime(ipMaturity) : (DateTime?)null;

        if (date1.HasValue && date1 >= DateTime.Now)
            e.Row.Cells[0].BackColor = System.Drawing.Color.White; // Theres no cell 4

        if (date1.HasValue && date1 < DateTime.Now)
            e.Row.Cells[0].BackColor = System.Drawing.Color.Red;
    }
}

protected void CheckBox1_CheckedChanged(object sender, EventArgs e) //from checkbox
{
    foreach (GridViewRow grRow in GridView1.Rows)
    {
        if (grRow.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkItem = (CheckBox)sender;
            // chkItem = (CheckBox)grRow.Cells[4].FindControl("CheckBox1"); // This would work if cell 4 has a CheckBox

            if (chkItem.Checked)
            {
                grRow.BackColor = Color.Black;
            }
        }
    }
}

private void DataBindGrid()
{
    var x = new List<IPMaturityData>();
    x.Add(new IPMaturityData() { ID = 1, IPMaturity = DateTime.Now.AddDays(-1) });
    x.Add(new IPMaturityData() { ID = 2, IPMaturity = DateTime.Now.AddDays(1) });
    GridView1.DataSource = x;
    GridView1.DataBind();
}

public class IPMaturityData
{
    public int ID { get; set; }

    public DateTime IPMaturity { get; set; }

    public bool CheckBox1 { get; set; } // This looks wrong, but on html it has "Checked='<%# Bind ("CheckBox1") %>"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM