Click here to Skip to main content
15,891,745 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Experts,
I Created a Custom Asp.net Gridview by following code:

XML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" GridLines="None"
                    onrowdeleting="GridView1_RowDeleting"
                    onrowdatabound="GridView1_RowDataBound" ondatabound="GridView1_DataBound"
                    onload="GridView1_Load" onrowcreated="GridView1_RowCreated"
                    ShowFooter="True">
                    <RowStyle BackColor="#EFF3FB" />
                    <Columns>
                        <asp:TemplateField HeaderText="SL">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("RowNumber") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("RowNumber") %>'></asp:TextBox>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Material">
                            <ItemTemplate>
                                <asp:DropDownList ID="drpMaterial" runat="server">
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Quantity">
                            <FooterTemplate>
                                <asp:Label ID="lblTotal" runat="server"></asp:Label>
                            </FooterTemplate>
                            <ItemTemplate>
                                <asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="True"
                                    ontextchanged="txtQuantity_TextChanged">0.00</asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                    ControlToValidate="txtQuantity" ErrorMessage="Required Field Missing">*</asp:RequiredFieldValidator>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Description">
                            <ItemTemplate>
                                <asp:TextBox ID="txtDescription" runat="server"
                                    ontextchanged="txtDescription_TextChanged1"></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Command">
                            <ItemTemplate>
                                <asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Add" />
                                <asp:Button ID="Button4" runat="server" Text="Delete" onclick="Button4_Click"
                                    CausesValidation="False" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <EmptyDataTemplate>
                        <asp:Button ID="Button1" runat="server" Text="btnAddNew" />
                        <asp:Button ID="Button2" runat="server" Text="btnDelete" />
                    </EmptyDataTemplate>
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <AlternatingRowStyle BackColor="White" />
                </asp:GridView>


and Used following c# code for operate the grid

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindwithgrid();
           
        }
       
    }
    dalMaterial dal = new dalMaterial();
    entMaterial ent = new entMaterial();
    private void bindwithgrid()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = ""; 
        dr["Column2"] = "";
        dr["Column3"] = "";
       
        dt.Rows.Add(dr);
        ViewState["CurrentTable"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }
    protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            Button lb = (Button)e.Row.FindControl("Button4");
            if (lb != null)
            {
                if (dt.Rows.Count > 1)
                {
                    if (e.Row.RowIndex == dt.Rows.Count - 1)
                    {
                        lb.Visible = true;
                    }
                }
                else
                {
                    lb.Visible = false;
                }
            }
        }
    }
    private void AddNewRowToGrid()
    {

    int rowIndex = 0;   
  
    if (ViewState["CurrentTable"] != null)   
    {   
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];   
       DataRow drCurrentRow = null;   
  
        if (dtCurrentTable.Rows.Count > 0)   
        {   
            foreach (DataRow row in dtCurrentTable.Rows)   
           {   
                foreach (GridViewRow grow in GridView1.Rows)   
               {   
                    if (rowIndex == grow.RowIndex + 1)   
                    {   
                      row["Column2"] = ((TextBox)grow.FindControl("txtQuantity")).Text;   
                      row["Column3"] = ((TextBox)grow.FindControl("txtDescription")).Text;   
                    }   
                }   

                DropDownList Material = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("drpMaterial");   
                TextBox Quantity = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");   
                TextBox Description = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDescription");   
  
                drCurrentRow = dtCurrentTable.NewRow();   
                drCurrentRow["RowNumber"] = rowIndex + 2;   
                if (Material != null)   
               {   
                 drCurrentRow["Column1"] = Material.SelectedValue;   
               }   
               drCurrentRow["Column2"] = Quantity.Text;   
               drCurrentRow["Column3"] = Description.Text;   
 
              rowIndex++;   
           }   
           dtCurrentTable.Rows.Add(drCurrentRow);   
 
           ViewState["CurrentTable"] = dtCurrentTable;   
  
            GridView1.DataSource = dtCurrentTable;   
            GridView1.DataBind();   

            SetPreviousData();   
        }   
    }   
   else  
    {   
       Response.Write("ViewState is null");   
    }   
  
    Response.Write(Session["i"]);   
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
     
        AddNewRowToGrid();
        Calculation();
       
    }
    private void SetPreviousData()
    {

        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
           
            DataTable dt = (DataTable)ViewState["CurrentTable"];

            if (dt.Rows.Count > 0)
            {
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    DropDownList Material = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("drpMaterial");
                    TextBox Quantity = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
                    TextBox Description = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDescription");
                    Material.SelectedValue = dt.Rows[i]["Column1"].ToString();
                    Quantity.Text = dt.Rows[i]["Column2"].ToString();
                    Description.Text = dt.Rows[i]["Column3"].ToString();
                    rowIndex++;
                }

            }

        }
    }
    protected void Button4_Click(object sender, EventArgs e)
    {

       Button lb = (Button)sender;
        GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
        int rowID = gvRow.RowIndex+1;

        if (ViewState["CurrentTable"] != null)
        {

            
            DataTable dt = new DataTable(); 
                dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 1)
            {
                if (gvRow.RowIndex < dt.Rows.Count - 1)
                {
                    int i = dt.Rows.Count;
                    dt.Rows.RemoveAt(rowID);
                }
            }
            if (dt.Rows.Count > 0)
            {
                int i = dt.Rows.Count;
            }
            ViewState["CurrentTable"] = dt;

         
            GridView1.DataSource = dt.DefaultView;
            GridView1.DataBind();
            SetPreviousData();
      Calculation();
          }
    }
  
    double total;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList Material = ((DropDownList)e.Row.FindControl("drpMaterial"));
            Material.DataSource = dal.SelectAll().Tables[0].DefaultView;
            Material.DataValueField = "id";
            Material.DataTextField = "name";
            Material.DataBind();
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblTotalPrice = (Label)e.Row.FindControl("lblTotal");

            lblTotalPrice.Text = total.ToString("N2");
        } 
    }
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
      
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
     
    }
    protected void GridView1_Load(object sender, EventArgs e)
    {
    }
    private void Calculation()
    {
       
        double total = 0.0;
    
        GridViewRow footerRow = GridView1.FooterRow;
        foreach (GridViewRow row in GridView1.Rows)
        {
            TextBox Quantity = ((TextBox)row.FindControl("txtQuantity"));

            total += double.Parse(Quantity.Text);
           
        }
        Label Total = ((Label)footerRow.FindControl("lblTotal"));
        Total.Text = total.ToString("N2");
         
    }
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        
        Calculation();
        foreach (GridViewRow row in GridView1.Rows)
        {
            TextBox Description = ((TextBox)row.FindControl("txtDescription"));

            Description.Focus();

        }
    }

}


My Problem is :
- When I delete Any row The Gridview also lost All the values of Last row.

- Another Problem Last Row Cannot be Delete.


Please help me to solve above problems

Thanks in advance
Mojam
Posted
Updated 5-Jun-10 2:14am
v3
Comments
Christian Graus 5-Jun-10 16:10pm    
Wow, John, you edited this without adding any sarcastic comments ? I am impressed.

1 solution

There is a ton of code to wade through here, none of it well written or formatted.

The delete button is (stupidly) called Button2. But the event that deletes a row is called Button4_Click. Your first step is to write readable code. Your second is to use your debugger to try to work out what is going wrong.

Your text, instead of saying 'Delete', says 'btnDelete' ? What on earth are you doing here ?

Buy a basic book on ASP.NET, it will explain the event args passed when you add a delete button the proper way, and how you can get the correct index of the row you clicked the button on. The rest of your issues should be perfectly clear to you when you run a debugger on this code. In future, read on how to do things properly, don't guess blindly. Just because it compiles, does not mean it will do what you hope, it will do what you asked it to.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900