Click here to Skip to main content
15,891,865 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have problems when creating new rows.I have a GridView 3 columns:
DropDownList (column name: ProductName), textbox (name column: Number), TextBox (column name: value) and Button Field to add new row with CommandName="addrow"
when the page loads,I bind Data into DropDownList.
The user will select the product name in DropDownList and enter the value into the textbox in the column named price,quantity.
After clicking LinkButtonField,a new row is added to the GridView.
But the value of previous row not stored.
Because for loop re-create controls of previous row(Dropdownlist,TextBox.
How to value of previous row not lost?
My code:
C#
//Product class
clsProduct p=new clsProduct();
DataTable dt; 
void LoadData()
{
        dt = //get data from table Product(idPro,ProName,.....)
        GridView2.DataSource = tbl;//table containt a row
        GridView2.DataBind();
        //Problem is here
        for (int i= 0; i < GridView2.Rows.Count; i++)
        {
            //Find DropDownList ProductName
            DropDownList cbo = (DropDownList)GridView2.Rows[cborow].Cells[0].FindControl("DrdProName");
            cbo.DataSource = dt;
            cbo.DataValueField = "idPro";
            cbo.DataTextField = "TProName";
            cbo.DataBind();
}

Make table for GridView:
C#
 void MakeTableGridView()
{
        if (tbl.Rows.Count == 0 || tbl==null)
        {
            tbl.Columns.Add("idPro", typeof(string));
            tbl.Columns.Add("quantity", typeof(int));
            tbl.Columns.Add("price", typeof(int));
            RowNew();
        }
}

New row:
C#
void RowNew()
    {

        dr = tbl.NewRow();
        dr[0] = "";
        dr[1] = "1";
        dr[2] = "0";
        tbl.AcceptChanges();
        tbl.Rows.Add(dr);
    }

Event when click AddRow LinkButtonField:
C#
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
        string cmd = e.CommandName;
        if (cmd =="addrow")
        {
            //Add New row in datatable
            RowNew();
            LoadData();
        }
}
Posted

1 solution

why are you not using editable gridview ?

you can use editable gridview and it will handeling everthing automatically.

this example can really helpful for you,

[Editable GridView in ASP.NET 2.0]
 
Share this answer
 
Comments
giatuan2011 18-Jun-12 6:55am    
Your solution is very effective.I'm trying to trap errors number format when the User enter wrong
[no name] 18-Jun-12 7:14am    
It will more helpfull to understand your problem if you can provide little more details :)

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