2

This is my program that page load the gridview and retrieve the database record to textbox and i put a add new button wish to add new row exactly like that row but the textbox is empty.

enter image description here

I wanted to create a new row in GridView while click add new button while my TextBox is retrieve data from database. I try to run the code but it is nothing happen when i click the button. Hope someone may help. Thanks.

My front end code

<Columns>
    <asp:TemplateField HeaderStyle-CssClass="display_none">
        <ItemTemplate>
            <asp:Label ID="Label3" runat="server" Font-Bold="true" Font-Size="Medium">Name</asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderStyle-CssClass="display_none">

        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" CssClass="NormalInputTextField" Text='<%#Eval("SLMN") %>'></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderStyle-CssClass="display_none">
    <ItemTemplate>
         <asp:Button ID="BtnDelete" runat="server" Text="Delete" CssClass="btn btn-primary" CommandName="remove" CommandArgument='<%# Container.DataItemIndex %>'/>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField FooterStyle-BorderStyle="None" HeaderStyle-CssClass="display_none">
    <ItemTemplate>
         <asp:Button ID="BtnSearch2" runat="server" Text="Search" CssClass="btn btn-primary"  CommandName="ViewComments" OnClientClick="javascript:saveData(this,'grid')"/>
    </ItemTemplate>
    <FooterStyle HorizontalAlign="Right" BorderStyle="None"/>
    <FooterTemplate>
         <asp:Button ID="BtnAdd" runat="server" Text="Add New Row" CssClass="btn btn-primary" OnClick="ButtonAdd_Click"/>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>

My back end code

private void AddNewRowToGrid()
{
     DataTable dt = new DataTable();
     DataRow dr = null;
     dt.Columns.Add(new DataColumn("Column1", typeof(string)));
     dt.Columns.Add(new DataColumn("Column2", typeof(string)));
     dr = dt.NewRow();
     dr["Column1"] = string.Empty;
     dr["Column2"] = string.Empty;
     dt.Rows.Add(dr);
}

My onclick event to call add new function

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}

My gridview tag

<grd:MultiSelectGridView ID="grid2" runat="server" Width="500px" 
                        CssClass="paging_gridview" AllowPaging="True" 
                        AutoGenerateColumns ="false" PageSize="10" PagerType="Custom"  
                        ShowFooter="true" OnRowDeleting="grid2_RowDeleting" 
                        MultiSelectDataKeyName="Urid,Name" ShowHeaderWhenEmpty="true"
                        MultiSelectColumnIndex="0" EnableMultiSelect="false" GridLines="None" BorderStyle="None" OnRowCommand="grid2_RowCommand"
                        >

i bind my record to gridview by page load

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

private void Loadgrid()
{
    string branch = txtBranch.Text.Trim();
    string name = txtName.Text.Trim();

    string sql = "SELECT * FROM fcs_cotmdl WHERE TMDL= '" + name + "'AND CONO='" + branch + "' ";

    SqlDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr_epsi"].ConnectionString;
    SqlDataSource2.ConnectionString = SqlDataSource2.ConnectionString.Replace("Provider=OraOLEDB.Oracle.1;", "");
    SqlDataSource con = new SqlDataSource();

    SqlDataSource2.SelectCommand = sql;
    grid2.DataSourceID = "SqlDataSource2";
    grid2.DataBind();
}
14
  • You create a new DataTable, add a single empty DataRow and then you're doing nothing with that table. Do you really expect that this code adds a new row to an existing DataSource? The right way is to load the DataSource from database since it could have been changed meanwhile. Then you can add another row easily. Afterwards you assign it as DataSource to your GridView and call DataBind. Commented Sep 10, 2015 at 7:17
  • I haven't looked at your wall of code yet, but the fact that you're instantiating a new DataTable instance instead of fetching an existing one looks rather fishy. Commented Sep 10, 2015 at 7:17
  • I dont see connection/binding between your datatable and gridview. Commented Sep 10, 2015 at 7:18
  • get your dataTable, through which you have bind your gridview, then add your newly created row to old datatable, Then rebind your gridview. Commented Sep 10, 2015 at 7:20
  • @TimSchmelter hi, im no idea on how to do it... i wanted the new row as same as the existing row that with database record in textbox but only if the new row textbox is empty.. Commented Sep 10, 2015 at 7:20

2 Answers 2

1

Following tutorial details the exact same scenario. Please refer to it. Adding Dynamic Rows to Gridview on Button Click

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++)
                {
                    //extract the TextBox values
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
 //Instead of all the textboxes, use the button as you require.
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                    dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                    dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }

And then the SetPreviousData() Function:

private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                    box1.Text = dt.Rows[i]["Column1"].ToString();
                    box2.Text = dt.Rows[i]["Column2"].ToString();
                    box3.Text = dt.Rows[i]["Column3"].ToString();

                    rowIndex++;
                }
            }
        }
    }

Then inside your Click Event:

protected void ButtonAdd_Click(object sender, EventArgs e)
  {
        AddNewRowToGrid();
  }
Sign up to request clarification or add additional context in comments.

Comments

1

From your Load grid method you should retrieve the data as a data table and bind to grid. And save in in session. Like this:

private void Loadgrid()
        {

            var dt = new DataTable();

            using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
            {

                var command = new SqlCommand();
                command.Connection = conn;
                command.CommandText = "SELECT * FROM [dbo].[T1]";
                command.CommandType = CommandType.Text;
                using (var adaptor = new SqlDataAdapter(command))
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    adaptor.Fill(dt);
                    if (conn.State == ConnectionState.Open) conn.Close();
                }

            }

                Session["ss"] = dt;
                grid2.DataSource = dt;
                grid2.DataBind();

            }


private void AddNewRowToGrid()
        {
            DataTable dt = (DataTable) Session["ss"];
            DataRow dr = null;
            DataRow newBlankRow1 = dt.NewRow();
            dt.Rows.Add(newBlankRow1);
            grid2.DataSource = dt;
            grid2.DataBind();

            Session["ss"] = dt;
        }

After add an empty row also you need to bind data to grid again.

1 Comment

DataTable dt = ToDataTable(res);-->> the res is not content in current context...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.