Home > Net >  How to insert multiple different textboxes to database table one by one for each row?
How to insert multiple different textboxes to database table one by one for each row?

Time:01-07

I have 3 different textboxes for serials. And when I click the button I want to save them for each row in database table.

Textbox1.Text="HP" ==> STOCKID   
Textbox2.Text="İ5" ==> MODEL   
Textbox3.Text="3" ==> QUANTITY   
Textbox4.Text="11231231"; ==> SERIAL-1   
Textbox5.Text="11231231"; ==> SERIAL-2   
Textbox6.Text="11231231"; ==> SERIAL-2   

Then Button click event.

Result should be as below.

FIRST GRIDVIEW

STOKID MODEL QUANTİTY
HP I5 3

SECOND GRIDVIEW

STOKID MODEL SERIALS DELETEBUTTON
HP I5 32165161 BUTTON
HP I5 12313223 BUTTON
HP I5 16516516 BUTTON

When I delete from serials one bye one, the first Gridview QTY should decrease one for each serials. Is it possible?
I use store procedure during insert to data for first gridview. But for second one I don't know how to use a loop for textboxes and add to database different serials(textboxes values).

CodePudding user response:

Ok, so say this markup:

We have Stokkid, model, and then have 3 optional serial num boxes (if they are left blank - we don't add).

So, this markup:

The boxes, and add button:

        <div style="float: left">
            <h4>Stokid</h4>
            <asp:TextBox ID="txtStokID" runat="server"></asp:TextBox>
        </div>
        <div style="float: left;margin-left:20px">
            <h4>Model</h4>
            <asp:TextBox ID="txtModel" runat="server"></asp:TextBox>
        </div>
        <div style="float: left;margin-left:20px">
            <h4>Serial 1</h4>
            <asp:TextBox ID="txtS1" runat="server"></asp:TextBox>
        </div>
        <div style="float: left;margin-left:20px">
            <h4>Serial 2</h4>
            <asp:TextBox ID="txtS2" runat="server"></asp:TextBox>
        </div>
        <div style="float: left;margin-left:20px">
            <h4>Serial 3</h4>
            <asp:TextBox ID="txtS3" runat="server"></asp:TextBox>
        </div>
        <div style="float: left;margin-left:20px;margin-top:20px">
            <asp:Button ID="cmdSave" runat="server" Text="Save/Add" CssClass="btn" 
                OnClick="cmdSave_Click"
                />
        </div>
        <div style="clear:both" ></div>

And right below that, 2 grids, the first totals gv, and then the data we have gv.

So, this:

        <h3>Counts</h3>
        <asp:GridView ID="GVCounts" runat="server" CssClass="table"
            width="40%" ShowHeaderWhenEmpty="True" >
        </asp:GridView>

        <h3>Items</h3>
        <asp:GridView ID="GridView1" runat="server" CssClass="table"
            width="40%" ShowHeaderWhenEmpty="True" >
        </asp:GridView>

And now our code to load up the above:

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

    void LoadData()
    {

        // load up "counts" grid
        string strSQL =
             @"SELECT Stokid, Model, count(*) as QTY FROM tblSerials 
               GROUP BY Stokid, Model";

        GVCounts.DataSource = MyRst(strSQL);
        GVCounts.DataBind();

        // Load up existing data grid

        strSQL =
             @"SELECT Stokid, Model, Serials FROM tblSerials ORDER BY ID";

        GridView1.DataSource = MyRst(strSQL);
        GridView1.DataBind();

    }

So, only part left is the "add new data button"

That code is this:

    protected void cmdSave_Click(object sender, EventArgs e)
    {
        // save (add) one row for each serial number, 
        // if no serial - then don't add

        DataTable dt = MyRst("SELECT * FROM tblSerials WHERE ID = 0");
        DataRow MyAddRow = dt.NewRow();
        MyAddRow["Stokid"] = txtStokID.Text;
        MyAddRow["Model"] = txtModel.Text;
        MyAddRow["Serials"] = txtS1.Text;

        dt.Rows.Add(MyAddRow);

        if (txtS2.Text != "")
        {
            MyAddRow = dt.NewRow();
            MyAddRow["Stokid"] = txtStokID.Text;
            MyAddRow["Model"] = txtModel.Text;
            MyAddRow["Serials"] = txtS2.Text;
            dt.Rows.Add(MyAddRow);
        }
        if (txtS3.Text != "")
        {
            MyAddRow = dt.NewRow();
            MyAddRow["Stokid"] = txtStokID.Text;
            MyAddRow["Model"] = txtModel.Text;
            MyAddRow["Serials"] = txtS3.Text;
            dt.Rows.Add(MyAddRow);
        }

        // send/save all rows to database
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblSerials", conn))
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
                SqlCommandBuilder daU = new SqlCommandBuilder(da);
                da.Update(dt);
            }
        }

        // Update counts and display
        LoadData();
    }

so, the result is now this:

enter image description here

Now, we do probably want to setup a delete button.

so, that means our "cheat" life and easy GV of data?

Well, we have to give it a bit more effort, love and care.

We need the database PK id, and we want that delete button.

And since the delete button can be a danger, then it should confirm.

So, we have to update our GV a bit, bite the bullet and use some templating. but, it is not much.

And lets use a boot-strap icon - they should be part of any most recent project by defualt. But BE warned, after boottrap 4, the later versions (due to some copyright/lawsuit, bootstrap does not include the glyph-icons).

Anyway, I COULD use a plain jane asp.net button in the gv for delete, but lets use standard html button - I ONLY use the html one, since I wanted the cute icon. Probably better for you to use a image button. (code is much the same either way).

So, our 2nd gv now looks like this:

<h3>Items</h3>
<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover"
    width="40%" ShowHeaderWhenEmpty="True" DataKeyNames="ID" 
    AutoGenerateColumns="False"  >
    <Columns>
        <asp:BoundField DataField="STOKID" HeaderText="STOKID"    />
        <asp:BoundField DataField="MODEL" HeaderText="MODEL"      />
        <asp:BoundField DataField="serials" HeaderText="serials"  />
        <asp:TemplateField HeaderText="Delete" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <button id="cmdDelete" runat="server" 
                    onclick="if (!confirm('Delete')) return false;"
                    onserverclick="cmdDel_ServerClick" >
                    <span aria-hidden="true" ></span>
                </button>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

And the code to load up this gv is now:

    void LoadData()
    {

        // load up "counts" grid
        string strSQL =
             @"SELECT Stokid, Model, count(*) as QTY FROM tblSerials 
               GROUP BY Stokid, Model";

        GVCounts.DataSource = MyRst(strSQL);
        GVCounts.DataBind();

        // Load up existing data grid

        strSQL = @"SELECT * FROM tblSerials ORDER BY ID";

        GridView1.DataSource = MyRst(strSQL);
        GridView1.DataBind();

    }

And our delete code is this:

    protected void cmdDel_ServerClick(object sender, EventArgs e)
    {

        HtmlButton btn = (HtmlButton)sender;
        GridViewRow gRow = (GridViewRow)btn.NamingContainer;

        int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
        string strSQL = "DELETE FROM tblSerial WHERE ID = {PKID}";
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                cmdSQL.ExecuteNonQuery();
            }
        }
        // update count and items gv
        LoadData();
    }

So, now we see, get this for a delete:

enter image description here

Edit2: The Myrst routine

In a few places in above, I also used this helper routine, since I get VERY tired VERY fast having to write code each and every time I want some data, so, I wrote and use this routine:

    DataTable MyRst(string strSQL)
    {
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
            }
        }
        return rstData;
    }

It handy for filling out a gridview, dropdown list etc.

  • Related