Home > Software engineering >  How to store information in the view list in the database
How to store information in the view list in the database

Time:03-07

How can I save rows created in the list view in my database? How can I access the values ​​in the (list view)? How to save the values ​​created in the view list to the database?

<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate runat="server">
        <tr >
            <td ></td>

            <td >
                <div >
                    <asp:Image ID="Image1" CssClass=" img" ImageUrl='<%# "../img/"   Eval("picture" )%>' runat="server" />
                </div>
            </td>

            <td ><%# Eval("namebook") %> </td>


           
                <td id="t_Plural" runat="server" ><%# Eval("Price") %> </td>
                
            



            <td ><%# Eval("titel") %></td>



            <td >


                <asp:Button ID="delete" CssClass="btn btn-outline-danger" CommandArgument='<%# Eval("id")%>' OnClick="delete_Click" runat="server" Text="حذف کالا" />


            </td>

            <td>
                <%--                                            <input id="quantity2" runat="server" type="number" AutoPostBack="true" oninput="lod_gheymat" onserverclick="lod_gheymat" value="" min="1" max="20" />--%>
                <asp:TextBox ID="quantity2" runat="server" CssClass="input-wrap" AutoPostBack="true" OnTextChanged="lod_gheymat" Text="1" min="1" max="20"></asp:TextBox>
            </td>

            <td >
                <div >
               <asp:Label ID="lbl_Plural" runat="server" Text="0"></asp:Label>&nbsp;&nbsp;&nbsp;&nbsp; <span > تومان</span>
                    </div>
            </td>
        </tr>

    </ItemTemplate>
</asp:ListView>

enter image description here

CodePudding user response:

protected void savetodatabase_Click(object sender, EventArgs e)
{

    System.Web.UI.HtmlControls.HtmlGenericControl Labelid;
    TextBox quantity2;
    foreach (ListViewItem rRow in ListView1.Items)
    {
        itemlist iteml = new itemlist();
        quantity2 = (TextBox)rRow.FindControl("quantity2");
        Labelid = (System.Web.UI.HtmlControls.HtmlGenericControl)rRow.FindControl("Labelid");
        iteml.quantity = quantity2.Text;
        iteml.bookid = Convert.ToInt32(Labelid.InnerText) ;
        iteml.Date = DateTime.Now;
        iteml.userid =  Convert.ToInt32(Session["userid"].ToString()) ;
        DatabaseContext context = new DatabaseContext();

        context.itemlists.Add(iteml);
        context.SaveChanges();

    }

}

CodePudding user response:

The way to approach this type of issue and problem is to NOT try and add to the database from the list view.

What you do is get your data (say in a data table).

then send the data table to the list view.

Now, if you want say a "add new row" button? Add the row to the data table, and then re-bind the list view.

Next up?

You asking how to add this to the database, but is not that where it came form in the first place?

and it is VERY confusing that you asking how to add rows to this LV, but how is the user going to add the picture?

Next up, how is this post getting up-votes? I will assume up-votes are not being messed with? I'll put this issue aside, but something not fitting here.

Ok, so, how to add rows, and how to save such rows back to the database?

You can achieve this goal this way:

First, we assume the LV can now be freely edit. That means using text boxes.

so, we have this markup:

(probably not HUGE important the LV you have, but the "idea" outlined here should work fine).

    <style> .borderhide input, textarea {border:none}</style>
    <div style="width:70%;padding:20px">
    <h2>Fighter Prints</h2>
    <asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
        <ItemTemplate>
            <tr style="">
                <td><asp:TextBox ID="Fighter" runat="server" Text='<%# Eval("Fighter") %>' TextMode="MultiLine" /></td>
                <td><asp:TextBox ID="Engine" runat="server" Text='<%# Eval("Engine") %>'   TextMode="MultiLine" Width="200px" /></td>
                <td><asp:TextBox ID="Thrust" runat="server" Text='<%# Eval("Thrust") %>'  Width="70px" /></td>
                <td><asp:TextBox ID="Description" runat="server" Text = '<%#Eval("Description") %>' 
                    TextMode="MultiLine" Width="340px" Rows="5"  /></td>
                <td>
                    <asp:Image ID="iPreview" runat="server" Height="68px" Width="149px" 
                        ImageUrl='<%# Eval("ImagePath") %>'/>
                </td>
                <td><asp:TextBox ID="Qty" runat="server" Text='<%# Eval("Qty") %>'  style="width:30px;text-align:right"/></td>
                <td><asp:TextBox ID="Price" runat="server" Text='<%# string.Format("{0:c2}",Eval("Price")) %>' style="Width:70px;text-align:right"/></td>
                <td><asp:TextBox ID="Total" runat="server" Text='<%# string.Format("{0:c2}",Eval("Total")) %>' style="Width:70px;text-align:right"  /></td>
            </tr>
        </ItemTemplate>
        <LayoutTemplate>
           <table id="itemPlaceholderContainer" runat="server" 
               >
               <tbody>
                <tr runat="server" style="" >
                    <th runat="server">Fighter</th>
                    <th runat="server">Engine</th>
                    <th runat="server">Thrust (lbs)</th>
                    <th runat="server">Description</th>
                    <th runat="server">Preview</th>
                    <th runat="server"  style="text-align:right">Qty</th>
                    <th runat="server" style="width:70px;text-align:right">Price</th>
                    <th runat="server" style="width:70px;text-align:right">Total</th>
                </tr>
                <tr id="itemPlaceholder" runat="server" />
               </tbody>
                 <tfoot>
                     <tr>
                         <td></td><td></td><td></td><td></td><td></td><td></td><td>Total</td>
                         <td><asp:TextBox ID="MyTotal" runat="server" Text="0" Width="70px" Style="text-align:right"></asp:TextBox></td>
                     </tr>
                </tfoot>
        </table>
        </LayoutTemplate>
        </asp:ListView>

Ok, so the code to load is now this:

    DataTable rstData = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGrid();
            Session["rstData"] = rstData;
        }
        else
            rstData = Session["rstData"] as DataTable;             
    }

    void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
            {
                conn.Open();
                rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                rstData.Columns.Add("Total", typeof(decimal),"[Qty] * [Price]");
                ListView1.DataSource = rstData;
                ListView1.DataBind();

                decimal myTotal = 0;
                foreach (ListViewItem OneRow in ListView1.Items)
                {
                    TextBox MyPrice = OneRow.FindControl("Total") as TextBox;
                    myTotal  = Decimal.Parse(MyPrice.Text, NumberStyles.Currency);
                }
                // now update the final total label
                TextBox lblTotal = ListView1.FindControl("MyTotal") as TextBox;
                lblTotal.Text = string.Format("{0:c2}", myTotal);
            }
        }
    }

And now we have this:

enter image description here

Ok, for the above, note how we added 3 buttons below the LV.

And becuase I wanted "cute" icons in the buttons, I dropped in hteml buttons, not asp.net ones. But, with a "id" and runat=server, they work JUST the same anyway.

So, our 3 buttons are (right after the LV markup)

        <div style="float:left">
            <button id="cmdSave" runat="server"  onserverclick="cmdSave_ServerClick">
                <span aria-hidden="true" ></span> &nbspSave
            </button>
            <button id="cmdUndo" runat="server"  style="margin-left:10px" onserverclick="cmdUndo_ServerClick">
                <span aria-hidden="true" ></span> &nbspUn do
            </button>
        </div>
        <div style="float:right">
            <button id="cmdAddNew" runat="server"  onserverclick="cmdAddNew_ServerClick">
                <span aria-hidden="true" ></span> &nbspAdd New
            </button>
        </div>

Ok, so of the 3, the un-do button code is easy:

    protected void cmdUndo_ServerClick(object sender, EventArgs e)
    {
        // undo changes - just re-load the lv
        LoadGrid();
    }

Ok, now the save button. This save button will:

save any new rows, and ALSO save any editing we do. Remember, since we used text boxes, then I can quite much tab around - edit ANY row. If I hit save, then we save all edits AND ALSO any new row added.

So, the save button does this:

    protected void cmdSave_ServerClick(object sender, EventArgs e)
    {
        GridToTable(); // send lv to table
        SaveToDatabase();
    }

So, now we need the routine to send the LV to the table. That code is this:

   void GridToTable()
    {
        // pull grid rows back to table.
        foreach (ListViewItem rRow in ListView1.Items)
        {
            int RecordPtr = rRow.DataItemIndex;
            DataRow OneDataRow;
            OneDataRow = rstData.Rows[RecordPtr];
            OneDataRow["Fighter"] = ((TextBox)rRow.FindControl("Fighter")).Text;
            OneDataRow["Engine"] = ((TextBox)rRow.FindControl("Engine")).Text;
            OneDataRow["Thrust"] = ((TextBox)rRow.FindControl("Thrust")).Text;
            OneDataRow["Description"] = ((TextBox)rRow.FindControl("Description")).Text;
            OneDataRow["Qty"] = ((TextBox)rRow.FindControl("Qty")).Text;
            OneDataRow["Price"] = Decimal.Parse(((TextBox)rRow.FindControl("Price")).Text,
                                  NumberStyles.Currency);
        }
    }

So, the above takes ANY edit - any row you edit, and send changes from LV->rstData.

So, now we need the rstData save all rows, all edits, all additions back to the database, and that code is this:

    void SaveToDatabase()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters", conn))
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
                SqlCommandBuilder daU = new SqlCommandBuilder(da);
                da.Update(rstData);                    
            }
        }
    }

So, now that is quite much all we need.

The last button, "add row" is also easy, and looks like this:

    protected void cmdAddNew_ServerClick(object sender, EventArgs e)
    {
        // user might have done some editing, so, pull LV to table
        // just in case
        GridToTable();

        // add new row to database
        DataRow MyNewRow = rstData.NewRow();
        // setup some defaults and values for this new row
        //MyNewRow["DateCreate"] = DateTime.Now;
        rstData.Rows.Add(MyNewRow);
        ListView1.DataSource = rstData;
        ListView1.DataBind();
    }

That is it. So, if I am looking at above LV, and hit add-new, we now have this:

enter image description here

so I can just fill out the information, and then hit save. If I hit un-do, then the row will not be added (nor saved).

Note how we had a min of code to do the save. Note how we did not mess with a boatload of templates (and thus save world poverty).

So, this works really nice, was not a lot of code and the real secrets "idea" here was persisting the rstData. This allows great ease of adding new rows, but MORE important it was very simple then to send the edits back to the database, and that one save command will not only save any editing in the LV, but also will create the new rows in the database for you. So, you can quite much tab around in that lv - almost like excel. So we don't have a huge mess of "edit" buttons, and all that jazz. Just a simple grid of data, and a simple save, or add new button.

Note VERY careful how the GridToTable works. As this shows HOW to grab, and get values from the LV, and that was quite much the "major" part of your question. So, you can grab any row of the LV, but to pull values out of the one row, you have to use "FindControl".

  • Related