Search code examples
c#sqlasp.netsql-serveruser-controls

Editing and updating a .NET DataList


I have an MS SQL Server database with some order information stored inside of it, and what I'm trying to be able to do is update the entries in the database through the GUI.

Right now, I'm loading the information once a user logs in with proper credentials, I can view all this data on the page and have two buttons, one for editing and one for updating the changes. However, each time I hit the edit button to enter edit mode, the page simply refreshes and the entry in the data list isn't editable.

Question: How can I make it so items rendered from my data list can be edited and then updated in my database through the GUI?

Markup:

<%@ Page Title="Login" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Lab3.Login" %>
<asp:Content runat="server" ContentPlaceHolderID="MainContent">
<table>
    <p>User username 'admin' and password 'admin' to view all orders</p>
    <tr>
        <td>
        username
    </td>
    <td>
        <asp:TextBox ID="userText" runat="server"></asp:TextBox>


      </td>
    </tr>

    <tr>
        <td>
            password
        </td>
        <td>
            <asp:TextBox ID="passwordText" runat="server" TextMode="Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="submitButton" runat="server" Text ="Login" OnClick="submitClick"/>
        </td>
    </tr>
 </table>
  <asp:DataList id="DataList1" runat="server" EnableViewState="true" OnEditCommand="DataList1_EditCommand" OnUpdateCommand="DataList1_UpdateCommand">
            <ItemTemplate>
                <b>First Name:</b> 
                <asp:Label id="FirstName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FirstName") %>'></asp:Label><br />

                <b>Last Name:</b> 
                <asp:Label id="LastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "LastName") %>'></asp:Label><br />


                <b>Food Item:</b>
                <asp:Label id="FoodItem" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FoodItem") %>'></asp:Label><br />

                <b>Address:</b>
                <asp:Label id="Address" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Address") %>'></asp:Label><br />

                <b>Phone Number:</b>
                <asp:Label id="PhoneNumber" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PhoneNumber") %>'></asp:Label><br />

                <asp:Button ID="Edit" runat="server" CommandName="Edit" Text="Edit"/>
                <asp:Button ID="Update" runat="server" CommandName="Update" Text="Update"/>

            </ItemTemplate>

            <HeaderTemplate>
                <asp:Label id="lblHeader" runat="server" Font-Names="Tahoma" ><h1>List of orders:</h1></asp:Label>
                <hr />
            </HeaderTemplate>
            <FooterTemplate>
                <hr />
            </FooterTemplate>
            <SeparatorTemplate>
                <hr />
            </SeparatorTemplate>
        </asp:DataList> 
    </asp:Content>

Code behind:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Providers.Entities;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Lab3
{

    public partial class Login : Page
    {
        string connect = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|food-truck.mdf;Integrated Security=True";
        SqlCommand getAllcomand = new SqlCommand();
        DataSet ds;

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

        protected void submitClick(object sender, EventArgs e)
        {
            SqlConnection foodDB = new SqlConnection(connect);
            string Username = userText.Text;
            string Password = passwordText.Text;

            SqlCommand compare = new SqlCommand();
            compare.Connection = foodDB;
            compare.CommandText = "select * from Users where Username='" + Username + "' and Password='" + Password + "'";
            foodDB.Open();

            SqlDataAdapter da = new SqlDataAdapter(compare);
            ds = new DataSet();
            da.Fill(ds);

            bool loginSuccessful = ((ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0));

            if (loginSuccessful)
            { 
                Console.WriteLine("Success!");
                bind();

            }
            else
            {
                Response.Write("Authentication failed!");
                Console.WriteLine("Invalid username or password");
            }
        }

        protected void bind()
        {
            string getAllQuery = "SELECT * from dbo.OrderTable";
            using (SqlConnection con = new SqlConnection(connect))
            {
                string[] checkarray = new string[100];

                SqlCommand command = new SqlCommand(getAllQuery, con);
                con.Open();
                SqlDataReader reader = command.ExecuteReader();
                DataList1.DataSource = reader;
                DataList1.DataBind();
            }
        }

        protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
        {
            DataList1.EditItemIndex = e.Item.ItemIndex;
            bind();
        }

        protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            bind();

        }

        protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
        {

        }
    }

}

Solution

  • you should add EditItemTemplate to DataList.

    <asp:DataList id="DataList1" runat="server" EnableViewState="true" OnItemCommand="dtlList_ItemCommand"><ItemTemplate>
                <b>First Name:</b> 
                <asp:Label id="FirstName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FirstName") %>'></asp:Label><br />
    
                <b>Last Name:</b> 
                <asp:Label id="LastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "LastName") %>'></asp:Label><br />
    
    
                <b>Food Item:</b>
                <asp:Label id="FoodItem" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FoodItem") %>'></asp:Label><br />
    
                <b>Address:</b>
                <asp:Label id="Address" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Address") %>'></asp:Label><br />
    
                <b>Phone Number:</b>
                <asp:Label id="PhoneNumber" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PhoneNumber") %>'></asp:Label><br />
    
                <asp:Button ID="Edit" runat="server" CommandName="Edit" Text="Edit"/>
    
    
            </ItemTemplate>
        <EditItemTemplate>
            <ItemTemplate>
                <b>First Name:</b> 
                <asp:TextBox id="FirstName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FirstName") %>'></asp:TextBox><br />
    
                <b>Last Name:</b> 
                <asp:TextBox id="LastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "LastName") %>'></asp:TextBox><br />
    
    
                <b>Food Item:</b>
                <asp:TextBox id="FoodItem" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FoodItem") %>'></asp:TextBox><br />
    
                <b>Address:</b>
                <asp:TextBox id="Address" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Address") %>'></asp:TextBox><br />
    
                <b>Phone Number:</b>
                <asp:TextBox id="PhoneNumber" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PhoneNumber") %>'></asp:TextBox><br />
    
    
                <asp:Button ID="Update" runat="server" CommandName="Update" Text="Update"/>
    
            </ItemTemplate>
        </EditItemTemplate>
    

    remove DataList1_EditCommand and update command. create OnItemCommand named dtlList_ItemCommand

    protected void dtlList_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("Edit"))
            {
                DataList1.EditItemIndex = e.Item.ItemIndex;
                bind();
            }
            else if (e.CommandName.Equals("Update"))
            {
                var dataListItem = DataList1.Items[DataList1.EditItemIndex];
                var name = ((TextBox)dataListItem.FindControl("FirstName")).Text;
                var lastName = ((TextBox)dataListItem.FindControl("FirstName")).Text;
                var footItem = ((TextBox)dataListItem.FindControl("FirstName")).Text;
                var address = ((TextBox)dataListItem.FindControl("FirstName")).Text;
                var phoneNumber = ((TextBox)dataListItem.FindControl("FirstName")).Text;
    
                // update operation
                // ... 
                DataList1.EditItemIndex = -1;
                bind();
            }
        }