How can I make Excel like grid in asp.net C# Webfo

2019-04-15 12:40发布

问题:

How can I make a grid like in Excel in ASP.NET WebForms?

I would like rows and columns where user can enter data and after a click on a save button the data would be inserted into a database.

回答1:

Hope this will help you out to full-fill your requirement.Here I am giving only aspx and c# coding. Create and modify your database and change the code accordingly.Here I am using direct insert statement you can use stored procedure.

Table in Database:-

page.aspx :-

<asp:GridView ID="excelgrd" runat="server" AutoGenerateColumns="false" ShowFooter="true">
            <Columns>
                <asp:BoundField DataField="Slno" HeaderText="SL No" />
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:TextBox ID="txnm" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                 <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:TextBox ID="txdesc" runat="server"></asp:TextBox>
                    </ItemTemplate>
                      <FooterStyle HorizontalAlign="Right" />
                      <FooterTemplate>
                       <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
                      </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="svbtn" runat="server" Text="Save" OnClick="svbtn_Click" />`

code behind of your page :-

`

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
             bindgrd();//bind your grid
        }
    }
    private void bindgrd()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("Slno", typeof(string)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Desc", typeof(string)));
        dr = dt.NewRow();
        dr["Slno"] = 1;
        dr["Name"] = string.Empty;
        dr["Desc"] = string.Empty;
        dt.Rows.Add(dr);
        //Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        excelgrd.DataSource = dt;
        excelgrd.DataBind();
    }
    protected void addnewrow()
    {
        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 tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
                    TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["Slno"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Name"] = tx1.Text;
                    dtCurrentTable.Rows[i - 1]["Desc"] = tx2.Text;

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

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

        //Set Previous Data on Postbacks
        SetPreviousData();
    }
    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 tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
                    TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");
                    tx1.Text = dt.Rows[i]["Name"].ToString();
                    tx2.Text = dt.Rows[i]["Desc"].ToString();

                    rowIndex++;
                }
            }
        }
    }
    protected void svbtn_Click(object sender, EventArgs e)
    {
        foreach(GridViewRow r in excelgrd.Rows)
        {
          string des =(r.FindControl("txdesc") as TextBox).Text;
          string nm = (r.FindControl("txnm") as TextBox).Text;
          try
          {
              con.Open();
              SqlCommand sql = new SqlCommand("insert into test (name,name_desc) values('"+nm+"','"+des+"')", con);
              sql.ExecuteNonQuery();
              sql.Dispose();
          }
          catch (Exception e1)
          {
              string error = e1.ToString();
          }
          finally
          {
              con.Close();

          }

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