[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Editing and Adding New Instances Of a Dropdownlist In a DATALIST.

Posted on 2004-10-10
1
Medium Priority
?
691 Views
Last Modified: 2011-09-20
Hello,

 I’m new to your site my name is Mathieu.

I have been posting this all over the net. I decided to join your site because every search brings me to you!

First of all I am using Visual Studio version 2002, Framework 1.1, version 1.1.4322 SP1  .I am working on a "DATALIST" not a GRID. I prefer the List to the Grid because I need things in the list to go vertically not horizontally. I have more information to have in the list then what is in the a grid.

I what I am trying to figure out is if I have to update the DATALIST or add a new instance of a dropdownlist .Also if I need to go back thought the list and edit the dropdownlist entry how do I achieve that? I prefer the list to the grid, I had a deadline no one on the other sites understood what I was saying. They kept answering me on how to use a datagrid.

I hope I explained myself well enough.

Thank You,
Feeling Lost,
Mathieu

Attached is my code..


THE UI CODE:


<%@ Page Codebehind="Objects.aspx.cs" Inherits="MSPOS.Objects"
Language="c#" AutoEventWireup="false" smartNavigation="True"%>
<%@ Register TagPrefix="mspos" TagName="footer"
Src="~/Engine/Controls/footer.ascx" %>
<%@ Register TagPrefix="mspos" TagName="header"
Src="Engine/Controls/header.ascx" %>
<%@ Register TagPrefix="uc1" TagName="logout"
Src="Engine/Controls/logout.ascx" %>
<HTML>
      <HEAD>
            <title>Objects</title>
            <meta content="True" name="vs_snapToGrid">
            <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
            <meta content="C#" name="CODE_LANGUAGE">
            <meta content="JavaScript (ECMAScript)"
name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
            <style type="text/css" ref="stylesheet">.tableItem { FONT: x-small
Verdana, Arial, sans-serif }
      .tableHeader { FONT: bold small Arial; COLOR: #663300;
BACKGROUND-COLOR: #cccc66 }
      .alternatingItem { FONT: x-small Verdana, Arial, sans-serif;
BACKGROUND-COLOR: #ffffcc }
      A { COLOR: #663300 }
      A:hover { COLOR: red }
      .pageLinks { FONT: bold x-small Verdana, Arial, sans-serif }
            </style>
      </HEAD>
      <body bgColor="#fef9e9" leftMargin="0" background="images/bg.gif"
topMargin="0" marginheigh="0"
            marginwidth="0">
            <mspos:header id="header" runat="server"></mspos:header>
            <center>
                  <form id="Form1" runat="server">
                        <table width=400>
                              <TBODY>
                                    <tr>
            <td>
                  <ASP:DataList CellSpacing="1" CellPadding="1" BorderWidth="3"
BorderColor="#CCCC99" width="100%"
                  font-names="Verdana" font-size="xx-small" BorderStyle="Outset"
GridLines="None" ShowFooter="True"
                  RepeatLayout="Flow" OnDeleteCommand="Delete_Command"
OnEditCommand="Edit_Command" OnCancelCommand="Cancel_Command"
                        RepeatDirection="Vertical" id="MyDataList" runat="server">
                        <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
                        <SelectedItemStyle Font-Bold="True" ForeColor="Beige"
BackColor="#FFCC66"></SelectedItemStyle>
                        <ItemStyle BackColor="Beige"></ItemStyle>
                        <HeaderStyle Font-Bold="True" ForeColor="White"
BackColor="#FFCC66"></HeaderStyle>
                        <EditItemStyle BackColor="yellow"></EditItemStyle>
                        <HeaderTemplate>
                              Objects
                        </HeaderTemplate>
                        <ItemTemplate>
                              <table width="400" style="font: 10pt verdana">
                                    <tr>
                                          <td>
                                                <tr><td>Object ID:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"CM_REF")) %></td></tr>
                                                <tr><td>Description:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"CM_DESCRIPTION")) %></td></tr>
                                                <tr><td>Name:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"CM_OBJECTNAME")) %></td></tr>
                                                <tr><td>Timeout:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"CM_TIMEOUT")) %></td></tr>
                                                <tr><td>Type:</td>
                                                <td><asp:DropDownList AutoPostBack="True" id="ddlCOMMANDTYPE"
DataSource='<%# BindTBCOMMANDTYPE() %>'
                                                selectedindex='<%#
GetSelectedIndexCOMMANDTYPE(DataBinder.Eval(Container.DataItem, "CT_REF").ToString())%>' runat="server"
                                                DataTextField="CT_DESCRIPTION"
DataValueField="CT_REF"></asp:DropDownList></td></tr>
                                                <tr><td>Content:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"CM_CONTENT"))%></td></tr>
                                                <tr><td>Prepared:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"CM_PREPARED"))  %></td></tr>
                                                <tr><td>Connection ID:</td>
                                                <td><%# Convert.ToString(DataBinder.Eval(Container.DataItem,
"DB_REF")) %></td></tr>
                                          </td>
                                    </tr>
                              </table>
                              <asp:LinkButton id="EditButton" Text="Edit" CommandName="Edit"
runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                              <table width=400 style="font: 10pt verdana">
                                    <tr>
                                          <td>
                                                <tr><td>Command ID:</td>
                                                <td><asp:TextBox id="CM_REFLabel" Text='<%#
DataBinder.Eval(Container.DataItem, "CM_REF") %>' runat="server"/></td></tr>
                                                <tr><td>Description:</td>
                                                <td><asp:TextBox id="CM_DESCRIPTIONTextBox" Text='<%#
DataBinder.Eval(Container.DataItem, "CM_DESCRIPTION") %>'
runat="server"/></td></tr>
                                                <tr><td>Name:</td>
                                                <td><asp:TextBox id="CM_OBJECTNAMETextBox" Text='<%#
DataBinder.Eval(Container.DataItem, "CM_OBJECTNAME") %>'
runat="server"/></td></tr>
                                                <tr><td>Timeout:</td>
                                                <td><asp:TextBox id="CM_TIMEOUTTextBox" Text='<%#
DataBinder.Eval(Container.DataItem, "CM_TIMEOUT") %>' runat="server"/></td></tr>
                                                <tr><td>Type:</td>
                                                <tr><td>Content:</td>
                                                <td><asp:TextBox id="CM_CONTENTTextBox" Text='<%#
DataBinder.Eval(Container.DataItem, "CM_CONTENT") %>' runat="server"/></td></tr>
                                                <tr><td>Prepared:</td>
                                                <td><asp:TextBox id="CM_PREPAREDTextBox" Text='<%#
DataBinder.Eval(Container.DataItem, "CM_PREPARED") %>' runat="server"/></td></tr>
                                                <tr><td>Connection ID:
                                                <td><asp:TextBox id="DB_REFTextBox" Text='<%#
DataBinder.Eval(Container.DataItem, "DB_REF") %>' runat="server"/></td></tr>
                                          </td>
                                    </tr>
                              </table>
                              <asp:LinkButton id="UpdateButton" Text="Update"
CommandName="Update" runat="server" />
                              <asp:LinkButton id="DeleteButton" Text="Delete"
CommandName="Delete" runat="server" />
                              <asp:LinkButton id="CancelButton" Text="Cancel"
CommandName="Cancel" runat="server" />
                        </EditItemTemplate>
                  </ASP:DataList>
                  <input type="hidden" id="PageSize" value="1" runat="server"
NAME="PageSize"> <input type="hidden" id="CurrentPage" value="1" runat="server"
NAME="CurrentPage">
                  <input type="hidden" id="TotalSize" runat="server" NAME="TotalSize">
                  <asp:LinkButton id="Prev" Text="<< Previous" OnClick="Page_DataList"
runat="server" />
                  &nbsp;
                  <asp:LinkButton id="Next" Text="Next >>" OnClick="Page_DataList"
runat="server" />
                  </form>
                  </TD></TR></TBODY></TABLE></center>
      </body>
</HTML>


THE CODE BEHIDE:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Data.Odbc;
using System.Text;

namespace MSPOS
{
      /// <summary>
      /// Summary description for Objects.
      /// </summary>
      public class Objects : System.Web.UI.Page
      {
            protected System.Web.UI.HtmlControls.HtmlForm Form1;
            private DataSet ddlDataSet1 = new DataSet();
            private DataSet ddlDataSet = new DataSet();
            protected Int32 _currentPageNumber = 1;
            protected System.Web.UI.WebControls.DataList MyDataList;
            protected System.Web.UI.WebControls.LinkButton Prev;
            protected System.Web.UI.WebControls.LinkButton Next;
            protected System.Web.UI.HtmlControls.HtmlInputHidden CurrentPage;
            protected System.Web.UI.HtmlControls.HtmlInputHidden TotalSize;
            protected System.Web.UI.HtmlControls.HtmlInputHidden PageSize;

            
//*********************************************************************
            // Get TBDATATYPE and populate dataset with DT_REF and DT_DESCRIPTION  
            

            
            public DataSet BindTBCOMMANDTYPE()
            {
                  OdbcConnection myConnection =  new
OdbcConnection("DSN=POS;UID=system;PWD=system");

                  // Populate the ddlDataSet1
                  myConnection.Open();
                  const string strSQLDDL = @"SELECT CT_REF, CT_DESCRIPTION FROM
TBCOMMANDTYPE ORDER BY CT_REF";
                  OdbcDataAdapter myDataAdapter = new OdbcDataAdapter(strSQLDDL,
myConnection);
                  ddlDataSet1.Clear();  
                  myDataAdapter.Fill(ddlDataSet1, "ddlCOMMANDTYPE");
                  myDataAdapter.Dispose();
                  myDataAdapter = null;
                  myConnection.Close();
                  return ddlDataSet1;
            }
            
//***********************************************************************

            public void Page_Load ( Object sender, EventArgs e )
            {
                  if ( !Page.IsPostBack )
                  {
                        BindData();
                  }
            }
 
            public void BindData()
            {
                  OdbcConnection myConnection =  new
OdbcConnection("DSN=POS;UID=system;PWD=system");
                  myConnection.Open();
                  // get records from the table
                  string commandString = @"SELECT CM_REF, CM_DESCRIPTION,
CM_OBJECTNAME, CM_TIMEOUT, CM_TYPE AS CT_REF, CM_CONTENT, CM_PREPARED, DB_REF FROM
TBCOMMANDS ORDER BY CM_REF";      
                  // Set the datagrid's datasource to the datareader and databind
                  // Create a OdbcCommand object and assign the connection connect to
the database
                  // Create a OdbcCommand object and assign the connection connect to
the database
                  OdbcCommand command = myConnection.CreateCommand( );
                  command.CommandText = commandString;
                  command.Connection = myConnection;
                  // Create the Reader and bind it to the datagrid
                  OdbcDataAdapter myDataAdapter = new OdbcDataAdapter(commandString,
myConnection);
                  //Fill the DataSet
                  DataSet ds = new DataSet();
                  //Get the startRecord Count
                  //Remember database count is zero based so first decrease the value
of
                  //the current page
                  int startRecord = ( int.Parse( CurrentPage.Value ) - 1 ) *
                        int.Parse( PageSize.Value );
                  //Fetch only the necessary records.
                  myDataAdapter.Fill( ds , startRecord , int.Parse( PageSize.Value ) ,
"TBCOMMANDS");
                  //DataBind the DataList    
                  MyDataList.DataSource = ds.Tables["TBCOMMANDS"].DefaultView;
                  MyDataList.DataBind();
                  myDataAdapter.Dispose();
                  myDataAdapter = null;
                  myConnection.Close();
                  

                  //Second Part
                  //Create a new Command to select the total number of records
                  OdbcCommand myCmd = new OdbcCommand( "SELECT Count(*) from
TBCOMMANDS",      myConnection );
                  myConnection.Open();
                  //retrieve the value
                  TotalSize.Value = myCmd.ExecuteScalar().ToString() ;
                  myConnection.Close();
                  BuildPagers();

 

                  
                  
            }
            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.MyDataList.SelectedIndexChanged += new
System.EventHandler(this.MyDataList_SelectedIndexChanged);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion


            public void Delete_Command(Object sender, DataListCommandEventArgs e)
            {

                  // Retrieve the name of the item to remove.
                  //                  String item = ((Label)e.Item.FindControl("ItemLabel")).Text;

                  // Filter the CartView for the selected item and remove it from
                  // the data source.
                  // Set the EditItemIndex property to -1 to exit editing mode. Be
sure
                  // to rebind the DataList to the data source to refresh the control.
                  MyDataList.EditItemIndex = -1;
                  BindData();

            }

            public void Edit_Command(Object sender, DataListCommandEventArgs e)
            {

                  // Set the EditItemIndex property to the index of the item clicked
                  // in the DataList control to enable editing for that item. Be sure
                  // to rebind the DataList to the data source to refresh the control.
                  MyDataList.EditItemIndex = e.Item.ItemIndex;
                  BindData();

            }

            public void Cancel_Command(Object sender, DataListCommandEventArgs e)
            {

                  // Set the EditItemIndex property to -1 to exit editing mode. Be
sure
                  // to rebind the DataList to the data source to refresh the control.
                  MyDataList.EditItemIndex = -1;
                  BindData();

            }

            private void MyDataList_SelectedIndexChanged(object sender,
System.EventArgs e)
            {
            
            }

            


            public int GetSelectedIndexCOMMANDTYPE (string CT_REF)
            {  
                  int iLoop;
                  DataTable dt = ddlDataSet1.Tables["ddlCOMMANDTYPE"];
                  for (iLoop=0; iLoop < dt.Rows.Count; iLoop++)
                  {  
                        string srow = dt.Rows[iLoop]["CT_REF"].ToString();
                        
                        if(srow == CT_REF)
                        {
                              return iLoop;
                        }  
                  };  
                  return 0;  
 
            }

            public void BuildPagers()
            {
                  //Check if its possible to have the previous page
                  if( ( int.Parse( CurrentPage.Value ) - 1 ) <= 0 )
                  {
                        Prev.Enabled = false;
                  }
                  else
                  {
                        Prev.Enabled = true ;
                  }
                  //Check if its possible to have the next page  
                  if( ( int.Parse( CurrentPage.Value ) * int.Parse( PageSize.Value ) )
                        >= int.Parse( TotalSize.Value ) )
                  {
                        Next.Enabled = false;
                  }
                  else
                  {
                        Next.Enabled = true ;
                  }
            }

            public void Page_DataList( object sender, EventArgs e )
            {
                  //Check for Button clicked
                  if( ((LinkButton)sender).ID == "Prev" )
                  {
                        //Check if we are on any page greater than 0
                        if( ( int.Parse( CurrentPage.Value ) - 1 ) >= 0 )
                        {
                              //Decrease the CurrentPage Value
                              CurrentPage.Value = ( int.Parse( CurrentPage.Value ) - 1
).ToString() ;
                        }
                  }
                  else if( ((LinkButton)sender).ID == "Next" )
                  {
                        //Check if we can display the next page.
                        if( ( int.Parse( CurrentPage.Value ) * int.Parse( PageSize.Value )
)
                              < int.Parse( TotalSize.Value ) )
                        {
                              //Increment the CurrentPage value
                              CurrentPage.Value = ( int.Parse( CurrentPage.Value ) + 1
).ToString() ;
                        }
                  }
                  //Rebuild the Grid
                  BindData();
            }
            



            
            
      }
}
0
Comment
Question by:mathieu_cupryk
1 Comment
 
LVL 2

Accepted Solution

by:
dwcorwith earned 1500 total points
ID: 12273005
With respect to your need to add an instance of a dropdownlist programatically:
Try the LoadControl method
Dim ctlMyDropDown as Control = LoadControl("cboMyDropDown")      (I'll let you convert it C#)

This works for user controls fine.  You will have to get it working for your dropdown list.  

To access the control, use FindControls.  Something like:
Dim ctl as Control = Page.FindControl("cboMyDropDown")
ctl.Visibility = True  
Now just access the property you want to set for the DropDown list.

I know it's not a complete answer, perhaps it will get you started.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Screencast - Getting to Know the Pipeline
Suggested Courses
Course of the Month19 days, 6 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question