locked
New Blank Gridview Row RRS feed

  • Question

  • User-705944790 posted

    I've written some code so that when a button is clicked in the grid it adds a new row, it all works perfectly until I add a checkbox, getting a cast error when the gridview databinds any help is appreciated.

    private void AddNewRowToGrid()
    {
    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

    DataRow drCurrentRow = null;

    if (dtCurrentTable.Rows.Count > 0)
    {
    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
    {
    Label box2 = (Label)gvBookItems.Rows[rowIndex].Cells[2].FindControl("lblEBookOutID");
    Label box3 = (Label)gvBookItems.Rows[rowIndex].Cells[3].FindControl("lblECopyNumber");
    Label box4 = (Label)gvBookItems.Rows[rowIndex].Cells[4].FindControl("lblEBookedOutDate");
    CheckBox box5 = (CheckBox)gvBookItems.Rows[rowIndex].Cells[5].FindControl("chkELTL");
    Label box6 = (Label)gvBookItems.Rows[rowIndex].Cells[6].FindControl("lblEBookedOutBy");
    drCurrentRow = dtCurrentTable.NewRow();
    rowIndex++;
    }
    dtCurrentTable.Rows.Add(drCurrentRow);
    ViewState["CurrentTable"] = dtCurrentTable;               
    gvBookItems.DataSource = dtCurrentTable;

    //Code is failing here........receiving cast error once it's created the new row...........
    gvBookItems.DataBind();

                }

            }
    else
    {

    Response.Write("ViewState is null");

            }

            SetPreviousData();

        }

    private void SetPreviousData()
        {
    int rowIndex = 0;
    i
    f (ViewState["CurrentTable"] != null)

            {

    DataTable dt = (DataTable)ViewState["CurrentTable"];

    if (dt.Rows.Count > 0)
    {

    for (int i = 0; i < dt.Rows.Count; i++)
    {

    if (i != dt.Rows.Count-1)
    {

    Label box2 = (Label)gvBookItems.Rows[rowIndex].Cells[2].FindControl("lblEBookOutID");
    Label box3 = (Label)gvBookItems.Rows[rowIndex].Cells[3].FindControl("lblECopyNumber");
    Label box4 = (Label)gvBookItems.Rows[rowIndex].Cells[4].FindControl("lblEBookedOutDate");
    CheckBox box5 = (CheckBox)gvBookItems.Rows[rowIndex].Cells[5].FindControl("chkELTL");
    Label box6 = (Label)gvBookItems.Rows[rowIndex].Cells[6].FindControl("lblEBookedOutBy");
    rowIndex++;
      }               

    else
        {
    Label box2 = (Label)gvBookItems.Rows[rowIndex].Cells[2].FindControl("lblEEBookOutID");
    TextBox box3 = (TextBox)gvBookItems.Rows[rowIndex].Cells[3].FindControl("txtEECopyNumber");
    TextBox box4 = (TextBox)gvBookItems.Rows[rowIndex].Cells[4].FindControl("txtEEBookedOutDate");
    CheckBox box5 = (CheckBox)gvBookItems.Rows[rowIndex].Cells[5].FindControl("chkEELTL");
    TextBox box6 = (TextBox)gvBookItems.Rows[rowIndex].Cells[6].FindControl("txtEEBookedOutBy");

     rowIndex++;

                        }

                    }

                }

            }

    Friday, September 30, 2016 2:03 PM

All replies

  • User36583972 posted

    Hi  RobM47,

    From your description, I have made a sample on my side. It is working.

    You can refer the following code.

    ASPX:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <%--<asp:CheckBox ID="CheckBox1" runat="server"
                                    AutoPostBack="true" 
                                    Text='<%# Eval("Checked").ToString() %>' />--%>
                                <asp:CheckBox ID="chkStatus" runat="server"
                                    AutoPostBack="true" 
                                    Checked='<%# Convert.ToBoolean(Eval("Checked").ToString().Equals("1") ? " True " : "False") %>'
                                    Text='<%# Eval("Checked").ToString().Equals("1") ? " Checked " : " Not Checked " %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="CustomerId" HeaderText="CustomerId" ItemStyle-Width="30" />
                        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
                        <asp:BoundField DataField="Count" HeaderText="Count" ItemStyle-Width="150" />
                    </Columns>
                </asp:GridView>

    ASPX.CS:

         protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    bind();
                }
            }
    
            private void bind()
            {
                DataTable tblDatas = new DataTable("Datas");
                DataColumn dc = null;
                dc = tblDatas.Columns.Add("CustomerId", Type.GetType("System.Int32"));
                dc = tblDatas.Columns.Add("Name", Type.GetType("System.String"));
                dc = tblDatas.Columns.Add("Count", Type.GetType("System.Int32"));
                dc = tblDatas.Columns.Add("Checked", Type.GetType("System.String"));
                DataRow newRow;
                for (int i = 0; i < 6; i++)
                {
                    newRow = tblDatas.NewRow();
                    newRow["CustomerId"] = i + 1;
                    newRow["Name"] = "Count" + i.ToString();
                    newRow["Count"] = 20 + (i * 2);
                    newRow["Checked"] = "1";
                    tblDatas.Rows.Add(newRow);
                }
                ViewState["dt"] = tblDatas;
                GridView1.DataSource = tblDatas;
                GridView1.DataBind();
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                int rowIndex = 0;
    
                DataTable dtCurrentTable = (DataTable)ViewState["dt"];
                if (dtCurrentTable.Rows.Count > 0)
                {
                    DataRow drCurrentRow = null;
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {       
                        drCurrentRow = dtCurrentTable.NewRow();
                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["dt"] = dtCurrentTable;
                    GridView1.DataSource = dtCurrentTable;
                    GridView1.DataBind();
    
                }
    
            }

    Best Regards,

    Yohann Lu

    Sunday, October 2, 2016 6:37 AM
  • User-705944790 posted

    Hi.
    Many thanks for your reply, this works great if you are not binding to a database, my version works if you don't connect to a database. The Checkboxes don't populate correctly as per the data. Having issues when pressing the Create button in the grid to add a new blank row for EditItemTemplate.

    My HTML is

    <asp:GridView ID="gvBookItems" runat="server" CssClass="ItemGridFormatting" AutoGenerateColumns="False" CellPadding="3" CellSpacing="3" Width="1200px" Height="60px" OnRowEditing="gvBookItems_RowEditing" OnRowCommand="gvBookItems_RowCommand">
    <
    Columns>
    <
    asp:TemplateField HeaderText="Edit Item">
    <
    ItemTemplate>
    <asp:ImageButton ID="imgbtnEditBI" runat="server" ImageUrl="~/Graphics/EditIcon.png" CommandName="Edit" ToolTip="Select record" />
    </
    ItemTemplate>
    <
    EditItemTemplate>
    <asp:ImageButton ID="imgbtnUpdateBI" runat="server" ImageUrl="~/Graphics/UpdateIcon.png" CommandName="UpdateBI" ToolTip="Update Booking Item"/>
    </
    EditItemTemplate>
    <
    ItemStyle HorizontalAlign="Center" Width="50px" />
    </asp:TemplateField>

    <
    asp:TemplateField HeaderText="Create">
    <
    ItemTemplate>
    <asp:ImageButton ID="imgbtnAddBI" runat="server" ImageUrl="~/Graphics/AddIcon.png" CommandName="CreateBI" ToolTip="Create Booking Item" />
    </
    ItemTemplate>
    <
    EditItemTemplate>
    <asp:ImageButton ID="imgbtnCanEdit" runat="server" CommandName="CancelEdit" ImageUrl="~/graphics/CancelIcon.png" ToolTip="Cancel Amendment" />
    </
    EditItemTemplate>
    <
    ItemStyle HorizontalAlign="Center" Width="40px" />                    </asp:TemplateField>

    <
    asp:TemplateField HeaderText="Book Out ID">
    <
    ItemTemplate>
    <asp:Label ID="lblEBookOutID" runat="server" Text='<%# Bind("BookOutID") %>'></asp:Label>
    </
    ItemTemplate>
    <
    EditItemTemplate>
    <asp:Label ID="lblEEBookOutID" runat="server" Text='<%# Bind("BookOutID") %>'></asp:Label>
    </
    EditItemTemplate>
    <
    ItemStyle Width="40px" HorizontalAlign="Center" />                     </asp:TemplateField>
    <
    asp:TemplateField HeaderText="Booked Out To">                     <ItemTemplate>
    <asp:Label ID="lblECustomerID" runat="server" Text='<%# Bind("CustomerID") %>'></asp:Label>
    </
    ItemTemplate>
    <
    EditItemTemplate>
    <asp:TextBox ID="txtEECustomerID" runat="server" Width="40px" CssClass="stdtextboxeshorizAlt" Text='<%# Bind("CustomerID") %>'></asp:TextBox>                      </EditItemTemplate>
    <
    ItemStyle Width="40px" HorizontalAlign="Center" />                      </asp:TemplateField>
    <
    asp:TemplateField HeaderText="Name">
    <
    ItemTemplate>
    <
    asp:Label ID="lblEName" runat="server" Text='<%# Bind("BookedName") %>'></asp:Label>
    </
    ItemTemplate>
    <
    EditItemTemplate>
    <
    asp:TextBox ID="txtEEName" runat="server" Width="200px" CssClass="stdtextboxeshorizAlt" Text='<%# Bind("BookedName") %>'></asp:TextBox>                      </EditItemTemplate>
    <
    ItemStyle Width="200px" HorizontalAlign="Center" />                     </asp:TemplateField>
    <
    asp:TemplateField HeaderText="LT Loan">
    <
    ItemTemplate>
    <asp:CheckBox ID="chkELTL" runat="server" Checked='<%# Convert.ToBoolean(Eval("LongTermLoan"))  %>' />
    </
    ItemTemplate>
    <
    EditItemTemplate>
    <asp:CheckBox ID="chkEELTL" runat="server" Checked='<%# Convert.ToBoolean(Eval("LongTermLoan")) %>'/>                      </EditItemTemplate>
    <
    ItemStyle Width="40px" HorizontalAlign="Center" />                     </asp:TemplateField>
    <
    asp:TemplateField HeaderText="Return Due">
    <
    ItemTemplate>
    <asp:Label ID="lblELoanRetDate" runat="server" Text='<%# Bind("LoanReturnDate","{0:dd/MM/yyyy}") %>'></asp:Label>                         </ItemTemplate>
    <
    EditItemTemplate>
    <asp:TextBox ID="txtEELoanRetDate" runat="server" Width="90px" CssClass="stdtextboxeshorizAlt" Text='<%# Bind("LoanReturnDate","{0:dd/MM/yyyy}") %>'></asp:TextBox>                     </EditItemTemplate>
    <
    ItemStyle Width="90px" HorizontalAlign="Center" />                     </asp:TemplateField>
    <
    asp:TemplateField HeaderText="Returned Date">                      <ItemTemplate>
    <asp:Label ID="lblEReturnedDate" runat="server" Text='<%# Bind("ReturnedDate","{0:dd/MM/yyyy}") %>'></asp:Label>                        </ItemTemplate>
    <
    EditItemTemplate>
    <asp:TextBox ID="txtEEReturnedDate" runat="server" Width="90px" CssClass="stdtextboxeshorizAlt" Text='<%# Bind("ReturnedDate","{0:dd/MM/yyyy}") %>'></asp:TextBox>
    </
    EditItemTemplate>
    <
    ItemStyle Width="90px" HorizontalAlign="Center" />                     </asp:TemplateField>
    </
    asp:GridView>

    C# Code is

    I do have try and catch etc, have also cut some of the names out to cut down the code

    A search button executes the following code which retrieves the main record, the following below retrieves the sub items

    protected bool RetrievePt2BookItems()
    {
    cmd = new SqlCommand("spBookItemsRetrieve", connASP);
    cmd.CommandType = CommandType.StoredProcedure;
    param = cmd.Parameters.Add("@ASPCI", SqlDbType.Int); 
    param.Value = txtConfigNumber.Text;
    connASP.Open();

    //I added the following code and receive a different error
                //SqlDataAdapter sda1 = new SqlDataAdapter(cmd);
    //DataTable tblBook = new DataTable();
    //DataColumn dc = null;
    //dc = tblBook.Columns.Add("@BookOutID", Type.GetType("System.Int32"))
    ;            //dc = tblBook.Columns.Add("@CustomerID", Type.GetType("System.Int32"));            //dc = tblBook.Columns.Add("@BookedName", Type.GetType("System.String"));            //dc = tblBook.Columns.Add("@LongTermLoan", Type.GetType("System.Boolean"));            //dc = tblBook.Columns.Add("@LoanReturnDate", Type.GetType("System.DateTime"));            //sda1.Fill(tblBook);
    //ViewState["dt"] = tblBook;
    //gvBookItems.DataSource = tblBook;
    //gvBookItems.DataBind();

    //I went back to this code

    SqlDataAdapter sda1 = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda1.Fill(dt);
    ViewState[
    "CurrentTable"] = dt;
    gvBookItems.DataSource = dt;
    gvBookItems.DataBind();
    }

    private void AddNewRowToGrid()
    {
    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null) { DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

    DataRow drCurrentRow = null;

    if (dtCurrentTable.Rows.Count > 0) { for (int i = 1; i <= dtCurrentTable.Rows.Count; i++) { Label box2 = (Label)gvBookItems.Rows[rowIndex].Cells[2].FindControl("lblEBookOutID"); Label box3 = (Label)gvBookItems.Rows[rowIndex].Cells[3].FindControl("lblECopyNumber"); Label box4 = (Label)gvBookItems.Rows[rowIndex].Cells[4].FindControl("lblEBookedOutDate"); CheckBox box5 = (CheckBox)gvBookItems.Rows[rowIndex].Cells[5].FindControl("chkELTL"); Label box6 = (Label)gvBookItems.Rows[rowIndex].Cells[6].FindControl("lblEBookedOutBy"); drCurrentRow = dtCurrentTable.NewRow(); rowIndex++; } dtCurrentTable.Rows.Add(drCurrentRow); ViewState["CurrentTable"] = dtCurrentTable;                gvBookItems.DataSource = dtCurrentTable;
    //Code is failing here........receiving cast error once it's created the new row........... gvBookItems.DataBind();

                }

            } else {

    Response.Write("ViewState is null");

            }

            SetPreviousData();

        }

    private void SetPreviousData()    
    {
    int rowIndex = 0;
    i
    f (ViewState["CurrentTable"] != null)

            {

    DataTable dt = (DataTable)ViewState["CurrentTable"];

    if (dt.Rows.Count > 0) {

    for (int i = 0; i < dt.Rows.Count; i++) {

    if (i != dt.Rows.Count-1) {

    Label box2 = (Label)gvBookItems.Rows[rowIndex].Cells[2].FindControl("lblEBookOutID"); Label box3 = (Label)gvBookItems.Rows[rowIndex].Cells[3].FindControl("lblECopyNumber"); Label box4 = (Label)gvBookItems.Rows[rowIndex].Cells[4].FindControl("lblEBookedOutDate"); CheckBox box5 = (CheckBox)gvBookItems.Rows[rowIndex].Cells[5].FindControl("chkELTL"); Label box6 = (Label)gvBookItems.Rows[rowIndex].Cells[6].FindControl("lblEBookedOutBy"); rowIndex++;   }               

    else     { Label box2 = (Label)gvBookItems.Rows[rowIndex].Cells[2].FindControl("lblEEBookOutID"); TextBox box3 = (TextBox)gvBookItems.Rows[rowIndex].Cells[3].FindControl("txtEECopyNumber"); TextBox box4 = (TextBox)gvBookItems.Rows[rowIndex].Cells[4].FindControl("txtEEBookedOutDate"); CheckBox box5 = (CheckBox)gvBookItems.Rows[rowIndex].Cells[5].FindControl("chkEELTL"); TextBox box6 = (TextBox)gvBookItems.Rows[rowIndex].Cells[6].FindControl("txtEEBookedOutBy");

     rowIndex++;

                        }

                    }

                }

            }


       

    protected void gvBookItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
    if (e.CommandName == "CreateBI")
    {
    GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
    index = gvBookItems.Rows.Count;
    ASPNo = txtConfigNumber.Text;
    gvBookItems.EditIndex = index;
    AddNewRowToGrid();
      }

    }

    The ERROR Message is Object cannot be cast from DBNull, this is when I click the CreateBI button in the grid to add a new row

     

    Monday, October 3, 2016 10:57 AM
  • User36583972 posted

    Hi RobM47,

    The ERROR Message is Object cannot be cast from DBNull, this is when I click the CreateBI button in the grid to add a new row

    I suggest you can add a check for the Object that like the below.

    if(Object ==  DBNull.Value)

    You can add RowDataBound event for your GridView and check which rows cause the cast error.

    RowDataBound Event in GridView in ASP.Net:

    http://www.c-sharpcorner.com/UploadFile/1e050f/rowdatabound-event-in-gridview-in-Asp-Net/

    Best Regards,

    Yohann Lu

    Wednesday, October 12, 2016 9:47 AM