Moshe Yalovsky
Moshe Yalovsky

Reputation: 183

DataList in ASP.NET Cancel Edit - How to get back to the item that was edited

The cancel event of a DataList has the following code

protected void Cancel_Command(Object sender, DataListCommandEventArgs e)
      {
         ItemsList.EditItemIndex = -1;
         BindList();
      }

After execution, the list is displayed from the first item. How can I move the current item of the list to the last item that was edited?

Thanks

Edit after comment from Sharham

This works - thanks, but it messes the pager that I am using for this DataList. Here is the code

protected void BindList()
      {

         // Set the data source and bind to the DataList control.
         GetSource();
         //ItemsList.DataSource = CartView;
         //SetPager();
         ItemsList.DataSource = pager;
         ItemsList.DataBind();

      }
      protected void GetSource()
      {
         ProductService productService = new ProductService();
         pager = new PagedDataSource();


         CartView = productService.GetAllProducts();
         SetPager();
         //CartView.Sort = "ProductName";

      }

      private void SetPager()
      {
         pager.AllowPaging = true;
         pager.PageSize = pageSize;
         pager.DataSource = CartView;
         pager.CurrentPageIndex = this.CurrentPage;
         this.next.Enabled = !pager.IsLastPage;
         this.prev.Enabled = !pager.IsFirstPage;
      }

How can handle correctly the pager after setting the datalist.SelectedIndex=e.Item.Itemindex;

Thanks

Updated

Here is the latest code that worked.

I still need to compare it with the previous code to pinpoint what was exactly the problem.

This solution shows how to use DataList with paging and editing. The "update" functionality was not added yet but it should be simple.

Employee.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="DataListPager.Employee" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<div>
   <table>
      <asp:DataList ID="DataList1" runat="server" OnEditCommand="DataList1_EditCommand" OnCancelCommand="DataList1_CancelCommand">
      <HeaderTemplate>
      <h3>Employees List</h3>
      </HeaderTemplate>
      <ItemTemplate>
         <tr>
            <td>
               <font color="Red"><b>Employee ID</b></font>
            </td>
            <td>
             <font color="Red"><b>LastName</b></font>
            </td>
         <td>
            <font color="Red"><b>Age</b></font>
         </td>
            <td>Action</td>
      
      </tr>
         <tr>
          <td>
            <font color="Green"><%# Eval("EmployeeID") %></font>
         </td>
         <td>
            <font color="Green"><%#Eval("LastName") %></font>
         </td>
         <td>
             <font color="Green"><%#Eval("age") %></font>
         </td>
         <td>
            <asp:Button ID="ButtonEdit" runat="server" Text="EDIT" CommandName="Edit" CausesValidation="true"  />
         </td>
      </ItemTemplate>
      <EditItemTemplate>
          <tr>
            <td>
               <font color="Red"><b>Employee ID</b></font>
            </td>
            <td>
             <font color="Red"><b>LastName</b></font>
            </td>
         <td>
            <font color="Red"><b>Age</b></font>
         </td>
      
      </tr>
         <tr>
          <td>
            <font color="Green"><%# Eval("EmployeeID") %></font>
         </td>
         <td>
            <font color="Green"><%#Eval("LastName") %></font>
         </td>
         <td>
              <asp:TextBox ID="txtAge" runat="server" style="margin-bottom: 0px" Text='<%# Bind("Age") %>'></asp:TextBox>
         </td>
            <td>
               <asp:Button ID="ButtonCancel" runat="server" CommandName="Cancel" Text="CANCEL" />
                
            </td>
     </tr>
       
      </EditItemTemplate>
   </asp:DataList>
    <tr>
    <td colspan="3">
           <%--<asp:Button ID="btnshow" runat="server" Height="32px" Text="Show"
            Font-Bold="true" Font-Size="12" ForeColor="DarkRed"
            Width="97px" onclick="btnshow_Click" />--%>
    </td>
    </tr>   
    <tr>
       <td colspan="3">
           <asp:Button ID="btnnext" runat="server" Height="32px" Text="Next"
            Font-Bold="true" Font-Size="12" ForeColor="DarkRed"
            Width="97px" onclick="btnnext_Click" />
           <asp:Button ID="btnprevious" runat="server" Height="32px" Text="Previous"
            Font-Bold="true" Font-Size="12" ForeColor="DarkRed"
            Width="97px" onclick="btnprevious_Click" />

       </td>
    </tr>
  </table>
    </div>
    </form>
</body>
</html>

Employee.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using DataListPager.App_Code;

namespace DataListPager
{
   public partial class Employee : System.Web.UI.Page
   {
      int position;
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            ViewState["vs"] = 0;
            DataBind();
         }
         position = (int)ViewState["vs"];
      }

      
      PagedDataSource pds;
      DataSet dset;
      
      //protected void btnshow_Click(object sender, EventArgs e)
      //{
      //   DataBind();
      //   btnnext.Visible = true;
      //   btnprevious.Visible = true;
      //}
      public void DataBind()
      {
          
         dset = new DataSet();
         EmployeeDS employeeDS = new EmployeeDS();
         dset = employeeDS.GetAllEmployees(); 
         pds = new PagedDataSource();
         //added
         pds.AllowPaging = true;
         pds.CurrentPageIndex = position;
         pds.PageSize = 2;
         ///
         pds.DataSource = dset.Tables[0].DefaultView;
         DataList1.DataSource = pds;
         DataList1.DataBind();
         btnnext.Visible = !pds.IsLastPage;
         btnprevious.Visible = !pds.IsFirstPage;
      }
      protected void btnprevious_Click(object sender, EventArgs e)
      {
         position = (int)ViewState["vs"];
         position--;
         ViewState["vs"] = position;
         DataBind();
      }

      protected void btnnext_Click(object sender, EventArgs e)
      {
         position = (int)ViewState["vs"];
         position++;
         ViewState["vs"] = position;
         DataBind();
         //btnnext.Visible = !pds.IsLastPage;
         //btnprevious.Visible = !pds.IsFirstPage;

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

         this.DataList1.EditItemIndex = -1;
         DataBind();
      }
   }
}

EmployeeDS.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OleDb;
namespace DataListPager.App_Code
{
   public class EmployeeDS
       
   {
      private OleDbConnection conn;
      public EmployeeDS()
      {
         this.conn = new OleDbConnection(Connect.getConnectionString());
     
      }
      public DataSet GetAllEmployees()
      {
         OleDbCommand objCmd = new OleDbCommand("EmployeeAll", conn);
         objCmd.CommandType = CommandType.StoredProcedure;
         DataSet ds = new DataSet();
         try
         {
            this.conn.Open();
            OleDbDataAdapter da = new OleDbDataAdapter(objCmd);
            da.Fill(ds);


         }
         catch (Exception e)
         {
            throw e;
         }
         finally
         {
            this.conn.Close();
         }
         return ds;
      }
   }
}

Connect.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DataListPager
{
   public class Connect
   {
      const string FILE_NAME = "Test.accdb";
      public static string getConnectionString()
      {
         //  string location = HttpContext.Current.Server.MapPath("@../../App_Data/" + FILE_NAME);
         string location = HttpContext.Current.Server.MapPath("~/App_Data/" + FILE_NAME);
         //         string location = HttpContext.Current.Server.MapPath(FILE_NAME);
         string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; data source=" + location; ;
         return ConnectionString;
      }
   }
}

Employee table

able: Employee                                                                                      Page: 1



Columns

         Name                                                  Type                        Size

         EmployeeID                                            Long Integer                             4
         LastName                                              Short Text                             255

         FirstName                                             Short Text                             255
         Age                                                   Long Integer                             4

EmployeeAll Query

uery: EmployeeAll                                                                                   Page: 1



SQL

         SELECT Employee.EmployeeID, Employee.LastName, Employee.FirstName,
         Employee.Age

Upvotes: 0

Views: 90

Answers (1)

Shahram Alemzadeh
Shahram Alemzadeh

Reputation: 1148

Made some modifications to your original code:

  • Used a SqlDataSource because every host supports SQL database and there is no point in using MS-Access on a web server.

  • Changed the table to Customers just because it has more records which makes paged results more meaningful.

  • Renamed the binding routine from DataBind to Bind to avoid any conflict with page_databind.

  • Added SelectedItemTemplate and SelectedItemStyle to datalist to make a visual feedback.

  • Added Update to datalist.

  • Disabled the paging buttons in edit mode.

The DataList:

<asp:DataList ID="DL" runat="server"
    DataKeyField="CustomerID"
    RepeatColumns="4"
    RepeatLayout="Table"
    OnEditCommand="DL_EditCommand"
    OnUpdateCommand="DL_UpdateCommand"
    OnCancelCommand="DL_CancelCommand">
    <ItemTemplate>
        <div style="border: 1px solid; padding: 3px; margin: 5px; background-color: linen;">
            <asp:Label ID="L1" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
            <br />
            <asp:Label ID="L2" runat="server" Text='<%# Eval("CompanyName") %>'></asp:Label>
            <br />
            <asp:Label ID="L3" runat="server" Text='<%# Eval("City") %>'></asp:Label>
            <br />
            <asp:Button ID="BT_EDIT" runat="server" CommandName="edit" Text="Edit" />
        </div>
    </ItemTemplate>
    <EditItemTemplate>
        <div style="padding: 3px; margin: 5px;">
            <asp:Label ID="L1" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
            <br />
            <asp:TextBox ID="TB2" runat="server" Text='<%#Eval("CompanyName") %>'></asp:TextBox>
            <br />
            <asp:TextBox ID="TB3" runat="server" Text='<%#Eval("City") %>'></asp:TextBox>
            <br />
            <asp:Button ID="BT_UPDATE" runat="server" CommandName="update" Text="Update" />
            <asp:Button ID="BT_CANCEL" runat="server" CommandName="cancel" Text="Cancel" />
        </div>
    </EditItemTemplate>
    <SelectedItemTemplate>
        <div style="border: 1px solid; padding: 3px; margin: 5px; background-color: linen;">
            <asp:Label ID="L1" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
            <br />
            <asp:Label ID="L2" runat="server" Text='<%# Eval("CompanyName") %>'></asp:Label>
            <br />
            <asp:Label ID="L3" runat="server" Text='<%# Eval("City") %>'></asp:Label>
            <br />
            <asp:Button ID="BT_EDIT" runat="server" CommandName="edit" Text="Edit" />
        </div>
    </SelectedItemTemplate>
    <SelectedItemStyle BorderStyle="Solid" BorderColor="Red" />
</asp:DataList>

The navigation buttons:

<div>
    <asp:Button ID="btnprevious" runat="server" Height="32px" Text="Previous"
        Font-Bold="true" Font-Size="12" ForeColor="DarkRed"
        Width="97px" OnClick="btnprevious_Click" />
    <asp:Button ID="btnnext" runat="server" Height="32px" Text="Next"
        Font-Bold="true" Font-Size="12" ForeColor="DarkRed"
        Width="97px" OnClick="btnnext_Click" />
</div>

The SqlDataSource:

<asp:SqlDataSource runat="server" ID="Customers_DS"
    ConnectionString="<%$ ConnectionStrings:NwindConnectionString %>"
    SelectCommand="SELECT [CustomerID], [CompanyName], [City] FROM [Customers]"
    DeleteCommand="DELETE FROM [CustomersTest] WHERE [CustomerID] = @original_CustomerID"
    InsertCommand="INSERT INTO [CustomersTest] ([CustomerID], [CompanyName], [City]) VALUES (@CustomerID, @CompanyName, @City)"
    UpdateCommand="UPDATE [CustomersTest] SET [CompanyName] = @CompanyName, [City] = @City WHERE [CustomerID] = @original_CustomerID">
    <DeleteParameters>
        <asp:Parameter Name="original_CustomerID" Type="String"></asp:Parameter>
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="CustomerID" Type="String"></asp:Parameter>
        <asp:Parameter Name="CompanyName" Type="String"></asp:Parameter>
        <asp:Parameter Name="City" Type="String"></asp:Parameter>
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="CompanyName" Type="String"></asp:Parameter>
        <asp:Parameter Name="City" Type="String"></asp:Parameter>
        <asp:Parameter Name="original_CustomerID" Type="String"></asp:Parameter>
    </UpdateParameters>
</asp:SqlDataSource>

The code behind:

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

int position;
PagedDataSource pds;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ViewState["vs"] = 0;
        Bind();
    }
    position = (int)ViewState["vs"];
}

public void Bind()
{
    pds = new PagedDataSource();
    pds.AllowPaging = true;
    pds.CurrentPageIndex = position;
    pds.PageSize = 12;
    pds.DataSource = Customers_DS.Select(new DataSourceSelectArguments());
    DL.DataSource = pds;
    DL.DataBind();
    btnnext.Enabled = !pds.IsLastPage;
    btnprevious.Enabled = !pds.IsFirstPage;
}

protected void DL_EditCommand(object source, DataListCommandEventArgs e)
{
    DL.EditItemIndex = e.Item.ItemIndex;
    Bind();
    btnnext.Enabled = false;
    btnprevious.Enabled = false;
}

protected void DL_UpdateCommand(object source, DataListCommandEventArgs e)
{
    string CustomerID = DL.DataKeys[e.Item.ItemIndex].ToString();
    TextBox CompanyName = (TextBox)e.Item.FindControl("TB2");
    TextBox City = (TextBox)e.Item.FindControl("TB3");

    Customers_DS.UpdateParameters["original_CustomerID"].DefaultValue = CustomerID;
    Customers_DS.UpdateParameters["CompanyName"].DefaultValue = CompanyName.Text;
    Customers_DS.UpdateParameters["City"].DefaultValue = City.Text;
    Customers_DS.Update();
    DL.EditItemIndex = -1;
    Bind();
    DL.SelectedIndex = e.Item.ItemIndex;
    btnnext.Enabled = !pds.IsLastPage;
    btnprevious.Enabled = !pds.IsFirstPage;
}

protected void DL_CancelCommand(object source, DataListCommandEventArgs e)
{
    DL.EditItemIndex = -1;
    Bind();
    DL.SelectedIndex = e.Item.ItemIndex;
    btnnext.Enabled = !pds.IsLastPage;
    btnprevious.Enabled = !pds.IsFirstPage;
}

protected void btnnext_Click(object sender, EventArgs e)
{
    position = (int)ViewState["vs"];
    position++;
    ViewState["vs"] = position;
    Bind();
    DL.SelectedIndex = -1;
}

protected void btnprevious_Click(object sender, EventArgs e)
{
    position = (int)ViewState["vs"];
    position--;
    ViewState["vs"] = position;
    Bind();
    DL.SelectedIndex = -1;
}

Upvotes: 0

Related Questions