Tag Archives: Table

[RESOLVED] Save Or Update in save page

can we save or update record in the table from the same page ???

Yes, we can.


Morzel

Yes we can without an issue.

[RESOLVED] autocomplete TextBox with data from a SQL SERVER

Hi all, im new at asp. net and im making a web page with 3 dropdownlist filtering DATA, and then i display a Gridview with the data selected. But i also have some TextBoxs and i want them to autocomplete according to the filters i previously selected. Im working all of this with no code behind.

Thank all, and here the code. I Bold The TextBox so you can see it clearly :D.

<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.OLEDB" %>
<%@ import Namespace="System.Data.OleDb.OleDbException" %>


<form id="form1" runat="server">


<asp:LinkButton ID="LinkButton5" runat="server" Text="Default"
    PostBackUrl="http://localhost:49724/Default.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton4" runat="server" Text="Editar/Actualizar/Eliminar Empleado"
    PostBackUrl="http://localhost:49724/EditEmpleado.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton7" runat="server" Text="Editar/Actualizar/Eliminar Producto"
    PostBackUrl="http://localhost:49724/EditProducto.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton8" runat="server" Text="Editar/Actualizar/Eliminar Categoria"
    PostBackUrl="http://localhost:49724/EditCategoria.aspx"></asp:LinkButton>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"


    SelectCommand="SELECT [PROJID] FROM [sxb_Proyectos] ORDER BY [PROJID]">


</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"


    SelectCommand="SELECT DISTINCT Ax50_Empleados.rut, Ax50_HorasRegistradas.rut
                    FROM Ax50_Empleados
                    INNER JOIN Ax50_HorasRegistradas
                    ON Ax50_Empleados.rut= Ax50_HorasRegistradas.rut
                    where ([PROJID] = CASE WHEN @PROJID = '-1' THEN [PROJID] ELSE @PROJID END)
                    ORDER BY Ax50_Empleados.rut">


<SelectParameters>


<asp:ControlParameter ControlID="DropDownList1" Name="PROJID" PropertyName="SelectedValue"/>


</SelectParameters>


</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"


    SelectCommand="SELECT DISTINCT sxb_Producto.Producto, Ax50_HorasRegistradas.LINEPROPERTYID
                    FROM sxb_Producto
                    INNER JOIN Ax50_HorasRegistradas
                    ON sxb_Producto.Producto = Ax50_HorasRegistradas.LINEPROPERTYID
                    where (([rut] = CASE WHEN @rut=  '-1' THEN [rut] ELSE @rut END)
                    AND
                    ([PROJID] = CASE WHEN @PROJID = '-1' THEN [PROJID] ELSE @PROJID END))
                    ORDER BY sxb_Producto.Producto">


<SelectParameters>


<asp:ControlParameter ControlID="DropDownList2" Name="rut" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList1" Name="PROJID" PropertyName="SelectedValue"/>


</SelectParameters>


</asp:SqlDataSource>


<table>
<tr>
<td>Proyecto</td>
<td>


<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1"  AppendDataBoundItems="true"
DataTextField="PROJID" DataValueField="PROJID">
<asp:ListItem Value="0"><Select an option></asp:ListItem>
<asp:ListItem Value="-1"><Select All></asp:ListItem>
                    

</asp:DropDownList>
</tr>


<tr>
<td>Rut Empleado</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2" AppendDataBoundItems="true" enableviewstate="false"
DataTextField="rut" DataValueField="rut">
<asp:ListItem Value="-1"><Select All></asp:ListItem>


</asp:Dropdownlist>


</td>
</tr>


<tr>
<td>Producto</td>
<td>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource3" AppendDataBoundItems="true" enableviewstate="false"
DataValueField="Producto" DataTextField="Producto">
<asp:ListItem Value="-1"><Select All></asp:ListItem>


</asp:DropDownList>
</td>
</tr>
</table>
<br />
<hr />
<table><tr><td>Codigo Proyecto</td><td>Nombre Proyecto</td><td>Cliente</td></tr>
<tr><td>
    

</td>
<td>
    <asp:textbox runat="server" ReadOnly="True"></asp:textbox>
</td>
<td>
    <asp:textbox runat="server"></asp:textbox>
</td>


</tr>
</table>
<hr />


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="PROJID"
    DataSourceID="SqlDataSource4"
    EmptyDataText="There are no data records to display."
    onrowectedindexchanged="GridView1_SelectedIndexChanged">
    <Columns>
        <asp:TemplateField>
        <ItemTemplate>
        <asp:LinkButton ID="Editar" Text="Editar" runat="server" CommandName="Edit"></asp:LinkButton>
        </ItemTemplate>
        <EditItemTemplate>
        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" AutoPostBack="True" AppendDataBoundItems="true" enableviewstate="false"
            Text="Actualizar"></asp:LinkButton>
        <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" AutoPostBack="True"
            Text="Cancelar"></asp:LinkButton>
        </EditItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="PROJID" HeaderText="PROJID"
            SortExpression="PROJID" />
        <asp:BoundField DataField="rut" HeaderText="rut"
            SortExpression="rut" />
        <asp:BoundField DataField="LINEPROPERTYID" HeaderText="LINEPROPERTYID"
            SortExpression="LINEPROPERTYID" />
        <asp:BoundField DataField="QTY" HeaderText="QTY" SortExpression="QTY" />
        <asp:BoundField DataField="TXT" HeaderText="TXT" SortExpression="TXT" />
        <asp:BoundField DataField="TRANSDATE" HeaderText="TRANSDATE"
            SortExpression="TRANSDATE" DataFormatString="{0:d}" />
        <asp:BoundField DataField="Comentario" HeaderText="Comentario"
            SortExpression="Comentario" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
    ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    ProviderName="<%$ ConnectionStrings:TestingConnectionString.ProviderName %>"
    SelectCommand="SELECT [PROJID], [rut], [LINEPROPERTYID], [QTY], [TXT], [TRANSDATE], [TRANSSTATUS], [DIMENSION], [DIMENSION3_], [Comentario]
                   FROM [Ax50_HorasRegistradas]
                   WHERE
                   (([rut] = CASE WHEN @rut=  '-1' THEN [rut] ELSE @rut END)
                   AND
                   ([PROJID] = CASE WHEN @PROJID = '-1' THEN [PROJID] ELSE @PROJID END)
                   AND
                   ([LINEPROPERTYID] = CASE WHEN @Producto = '-1' THEN [LINEPROPERTYID] ELSE @Producto END))"


     UpdateCommand="UPDATE [Ax50_HorasRegistradas] set Comentario = @Comentario WHERE PROJID = @PROJID AND TRANSDATE = @TRANSDATE">


<UpdateParameters>
<asp:Parameter Name="PROJID" />
<asp:Parameter Name="TRANSDATE" />
</UpdateParameters>


<SelectParameters>
<asp:ControlParameter ControlID="DropDownList2" Name="rut" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList1" Name="PROJID" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList3" Name="Producto" PropertyName="SelectedValue"/>
</SelectParameters>


</asp:SqlDataSource>
</form>


well it didnt bold the text box because i think is pasted codes, so the lines of the textbox are 107 and 110.

thank so much

Hi,


Check below links,


http://www.aspdotnetcodes.com/AutoComplete_From_Database.aspx

http://www.developerbarn.com/net-code-samples/75-using-ajax-auto-complete-extender-database.html



You can use ajax extensions and  web services:

.aspx page:

<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajaxToolkit:ToolkitScriptManager>
  <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"
            ServiceMethod="GetProducts" ServicePath="WebService.asmx" TargetControlID="txtSearch"> </ajaxToolkit:AutoCompleteExtender>
          </div>


WebService.cs:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
    public WebService()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
    [WebMethod]
    public string[] GetProducts(string prefixText)
    {
       
            string sql = "Select rut from table Where rut like @prefixText";
            SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["TestingConnectionString"].ToString());
            da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.NVarChar, 50).Value = prefixText + "%";
            DataTable dt = new DataTable();
            da.Fill(dt);
            string[] items = new string[dt.Rows.Count];
            int i = 0;
            foreach (DataRow dr in dt.Rows)
            {
                items.SetValue(dr["rut"].ToString(), i);
                i++;
            }
            return items;

        }


       
    }




 

 

hi, thanks for answering but with ajax it doesnt work, y pasted the code like this. 

<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.OLEDB" %>
<%@ import Namespace="System.Data.OleDb.OleDbException" %>


<script>


<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajaxToolkit:ToolkitScriptManager>
  <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"
            ServiceMethod="GetProducts" ServicePath="WebService.asmx" TargetControlID="txtSearch"> </ajaxToolkit:AutoCompleteExtender>
          </div>


</script>






<form id="form1" runat="server">


<asp:LinkButton ID="LinkButton5" runat="server" Text="Default"
    PostBackUrl="http://localhost:49724/Default.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton4" runat="server" Text="Editar/Actualizar/Eliminar Empleado"
    PostBackUrl="http://localhost:49724/EditEmpleado.aspx"></asp:LinkButton>


............


and it give me an error "Etiqueta de servidor 'ajaxToolkit:ToolkitScriptManager' desconocida."

it doesnt recognize the ajaxtoolkit

Did you download and configure the ajax control toolkit with your Visual studio?

if not, you can download from here:

 http://www.asp.net/ajaxlibrary/act.ashx

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

 

 

 

 

ok i did all the steps of ajax and nothing happens,now i have this.


<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>


<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.OLEDB" %>
<%@ import Namespace="System.Data.OleDb.OleDbException" %>
<%@ Import Namespace="AjaxControlToolkit" %>


 <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>
  <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"
            ServiceMethod="GetProducts" ServicePath="WebService.asmx" TargetControlID="txtSearch"> </ajaxToolkit:AutoCompleteExtender>
  </div>




<form id="form1" runat="server">


<asp:LinkButton ID="LinkButton5" runat="server" Text="Default"
    PostBackUrl="http://localhost:49724/Default.aspx"></asp:LinkButton>
<br />
.
.
.
.
.
.


thanks very much for your help :D

Did you add the webservice.cs (with the GetProducts method) file in the app_code folder ?

if you did already, please mark out the line and start debugging and see if that is calling or not.....

i have the webservice in the same folder as the aspx web page, but what is that of getProducts method? it is something that i have to add as a line, its a file?


thank you for your time.

Please see my first reply.....you can see the GetProducts method there....

public string[] GetProducts(string prefixText)
    {......}


 

hi, and thanks for answering.

i have this for the moment in the aspx file.

<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.OLEDB" %>
<%@ import Namespace="System.Data.OleDb.OleDbException" %>
<%@ Import Namespace="AjaxControlToolkit" %>


<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>
  <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"
            ServiceMethod="GetProducts" ServicePath="WebService.asmx" TargetControlID="txtSearch"> </ajaxToolkit:AutoCompleteExtender>
  </div>


<form id="form1" runat="server">


<asp:LinkButton ID="LinkButton5" runat="server" Text="Default"
    PostBackUrl="http://localhost:49724/Default.aspx"></asp:LinkButton>
<br />


and this in the .cs file

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

/// <summary>  
/// Summary description for WebService  
/// </summary>  
[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
    public WebService(prefixText)
    {
        //Uncomment the following line if using designed components  
        //InitializeComponent();  
    }
    [WebMethod]
    public string[] GetProducts(string prefixText)
    {

        string sql = "Select rut from table Where rut like @prefixText";
        SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["TestingConnectionString"].ToString());
        da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.NVarChar, 50).Value = prefixText + "%";
        DataTable dt = new DataTable();
        da.Fill(dt);
        string[] items = new string[dt.Rows.Count];
        int i = 0;
        foreach (DataRow dr in dt.Rows)
        {
            items.SetValue(dr["rut"].ToString(), i);
            i++;
        }
        return items;

    }



}


and it gives me this error when i debug

Mensaje de error del analizador: Etiqueta de servidor 'ajaxToolkit:ToolkitScriptManager' desconocida.

Error de código fuente: 

Línea 7:  <%@ Import Namespace="AjaxControlToolkit" %>
Línea 8:  
Línea 9:  <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>   
Línea 10:   <div>    
Línea 11:     <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> 

thanks for your answer


hi there, i still have this error and i did all of the ajax tools stuff

Línea 9:
Línea 10:
Línea 11: <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
Línea 12:   <div>
Línea 13:     <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>

this is my code. 


<%@ Import Namespace="AjaxControlToolkit" %>



<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
  <div>    
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>    
    <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"     
            ServiceMethod="GetProducts" ServicePath="WebService.cs" TargetControlID="txtSearch"> </ajaxToolkit:AutoCompleteExtender>    
  </div> 
</ajaxToolkit:ToolkitScriptManager> 
<form id="form1" runat="server">



i change the code to this and i can see the page now, but the text doesnt show anything.

<%@ Import Namespace="AjaxControlToolkit" %>


<form id="form1" runat="server">


<ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
  <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"
            ServiceMethod="GetProducts" ServicePath="WebService.cs" TargetControlID="txtSearch"> </AutoCompleteExtender>
  </div>
</ToolkitScriptManager>



Hello,

please read my first post carefully and see there the servicepath="Webservice.asmx"....put the code inside the webservice.cs file! 

great thanks so much!

show data in a textbox automatically when i choose an item in a dropdownlist

hi all, i have a web page, with some filters using dropdownlist, and when i select items from these dropdownlist, a gridview appear showing data from a sql server. The idea is that when i select an item, from the first or second drop down list, in a textbox appear for example the name of the item i choose from the dropdownlist.

Thanks all for your help. Here is the code. I use only VB and not C#.

<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.OLEDB" %>
<%@ import Namespace="System.Data.OleDb.OleDbException" %>
<%@ import Namespace="System.Web.UI.WebControls.DataControlFieldCollection" %>
<%@ import Namespace="System.Web.UI.HtmlControls.HtmlGenericControl" %>


<script runat="server">
    

    Dim Proyectos As SqlDataSource
    

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    

        Proyectos = New SqlDataSource
        

        Dim sConnString As String
        sConnString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("TestingConnectionString").ConnectionString
        Proyectos.ConnectionString = sConnString
        Proyectos.ID = "Proyectos"
        

        ' Now configure the INSERT statement. We have to declare the Parameters here
        Proyectos.InsertCommand = "INSERT INTO [sxb_Conocimiento] ([Rut],[IdProducto],[IdCategoria],[Experiencia]) VALUES (@Rut, @IdProducto, @IdCategoria, @Experiencia)"
        Proyectos.InsertParameters.Add("Rut", "")
        Proyectos.InsertParameters.Add("IdProducto", "")
        Proyectos.InsertParameters.Add("IdCategoria", "")
        Proyectos.InsertParameters.Add("Experiencia", "")
        

        Me.Controls.Add(Proyectos)
  

    End Sub
    

    ' The following code is triggered when the Insert button is pressed.
    Protected Sub bInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ' Clear insert Parameters
        Proyectos.InsertParameters.Clear()
        ' Add parameters with values form Text boxes
        Proyectos.InsertParameters.Add("Rut", Rut.Text.ToString)
        Proyectos.InsertParameters.Add("IdProducto", IdProducto.Text.ToString)
        Proyectos.InsertParameters.Add("IdCategoria", IdCategoria.Text.ToString)
        Proyectos.InsertParameters.Add("Experiencia", Experiencia.Text.ToString)
        ' Do the INSERT command
        Proyectos.Insert()
    End Sub


</script>


<form id="form1" runat="server">


<asp:LinkButton ID="LinkButton5" runat="server" Text="Default"
    PostBackUrl="http://localhost:49724/Default.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton4" runat="server" Text="Editar/Actualizar/Eliminar Empleado"
    PostBackUrl="http://localhost:49724/EditEmpleado.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton7" runat="server" Text="Editar/Actualizar/Eliminar Producto"
    PostBackUrl="http://localhost:49724/EditProducto.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton8" runat="server" Text="Editar/Actualizar/Eliminar Categoria"
    PostBackUrl="http://localhost:49724/EditCategoria.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton9" runat="server" Text="Editar/Actualizar/Eliminar Valores"
    PostBackUrl="http://localhost:49724/EditValores.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton10" runat="server" Text="Editar/Actualizar/Eliminar Conocimiento"
    PostBackUrl="http://localhost:49724/EditConocimiento.aspx"></asp:LinkButton>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT DISTINCT [Rut] FROM [sxb_Conocimiento]
                    ORDER BY [Rut]">
</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT DISTINCT [IdProducto] FROM [sxb_Conocimiento]
                    WHERE ([Rut] = CASE WHEN @Rut = '-1' THEN [Rut] ELSE @Rut END)
                    ORDER BY [IdProducto]">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Rut" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT DISTINCT [IdCategoria] FROM [sxb_Conocimiento]
                    WHERE
                    (([Rut] = CASE WHEN @Rut = '-1' THEN [Rut] ELSE @Rut END)
                    AND
                    ([IdProducto] = CASE WHEN @IdProducto = '-1' THEN [IdProducto] ELSE @IdProducto END))
                    ORDER BY [IdCategoria]">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Rut" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList2" Name="IdProducto" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT DISTINCT [Experiencia] FROM [sxb_Conocimiento]
                    WHERE
                    (([Rut] = CASE WHEN @Rut = '-1' THEN [Rut] ELSE @Rut END)
                    AND
                    ([IdProducto] = CASE WHEN @IdProducto = '-1' THEN [IdProducto] ELSE @IdProducto END)
                    AND
                    ([IdCategoria] = CASE WHEN @IdCategoria = '-1' THEN [IdCategoria] ELSE @IdCategoria END))
                    ORDER BY [Experiencia]">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Rut" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList1" Name="IdProducto" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList1" Name="IdCategoria" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>


<table>
<tr>
<td>Rut</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
        DataSourceID="SqlDataSource1"  AppendDataBoundItems="true" enableviewstate="false"
DataTextField="Rut" DataValueField="Rut" DataTextFormatString="{0}">
<asp:ListItem Value="0"><Select an option></asp:ListItem>
<asp:ListItem Value="-1"><Select All></asp:ListItem>
</asp:DropDownList>
</tr>


<tr>
<td>Producto</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2" AppendDataBoundItems="true" enableviewstate="false"
DataTextField="IdProducto" DataValueField="IdProducto">
<asp:ListItem Value="-1"><Select All></asp:ListItem>
</asp:Dropdownlist>
</td>
</tr>


<tr>
<td>Categoria</td>
<td>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource3" AppendDataBoundItems="true" enableviewstate="false"
DataTextField="IdCategoria" DataValueField="IdCategoria">
<asp:ListItem Value="-1"><Select All></asp:ListItem>
</asp:Dropdownlist>
</td>
</tr>


<tr>
<td>Experiencia</td>
<td>
<asp:DropDownList ID="DropDownList4" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource4" AppendDataBoundItems="true" enableviewstate="false"
DataTextField="Experiencia" DataValueField="Experiencia">
<asp:ListItem Value="-1"><Select All></asp:ListItem>
</asp:Dropdownlist>
</td>
</tr>
</table>


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoPostBack="True" DataKeyNames="Rut" enableviewstate="false" AppendDataBoundItems="true"
    DataSourceID="SqlDataSource5"
    EmptyDataText="There are no data records to display.">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:LinkButton ID="Editar" Text="Editar" runat="server" CommandName="Edit"></asp:LinkButton>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" AutoPostBack="True" AppendDataBoundItems="true" enableviewstate="false"
        Text="Actualizar"></asp:LinkButton>
    <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" AutoPostBack="True"
        Text="Cancelar"></asp:LinkButton>
    </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:LinkButton ID="Apagar" Text="Eliminar" runat="server" CommandName="Delete" OnClientClick='return confirm("Esta seguro que quiere borrar este registro?");' AutoPostBack="True" enableviewstate="false" CausesValidation="false"></asp:LinkButton>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Rut" HeaderText="Rut" SortExpression="Rut" />
    <asp:BoundField DataField="IdProducto" HeaderText="IdProducto" SortExpression="IdProducto" />
    <asp:BoundField DataField="IdCategoria" HeaderText="IdCategoria"
        SortExpression="IdCategoria" />
    <asp:BoundField DataField="Experiencia" HeaderText="Experiencia"
        SortExpression="Experiencia" />
    <asp:BoundField DataField="Resultado" HeaderText="Resultado"
        SortExpression="Resultado" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
    ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    ProviderName="<%$ ConnectionStrings:TestingConnectionString.ProviderName %>"
    SelectCommand="SELECT DISTINCT [Rut], [IdProducto], [IdCategoria], [Experiencia], [Resultado] FROM [sxb_Conocimiento]
                   WHERE
                   (([Rut] = CASE WHEN @Rut= '-1' THEN [Rut] ELSE @Rut END)
                   AND
                   ([IdProducto] = CASE WHEN @IdProducto = '-1' THEN [IdProducto] ELSE @IdProducto END)
                   AND
                   ([IdCategoria] = CASE WHEN @IdCategoria = '-1' THEN [IdCategoria] ELSE @IdCategoria END)
                   AND
                   ([Experiencia] = CASE WHEN @Experiencia = '-1' THEN [Experiencia] ELSE @Experiencia END))"


    UpdateCommand="UPDATE [sxb_Conocimiento] set IdProducto = @IdProducto, IdCategoria = @IdCategoria, Experiencia = @Experiencia where Rut = @Rut"


    InsertCommand="INSERT INTO [sxb_Conocimiento] (Rut, IdProducto, IdCategoria, Experiencia) VALUES (@Rut, @IdProducto, @IdCategoria, @Experiencia)"


    DeleteCommand="DELETE from [sxb_Conocimiento] where Rut = @Rut">


    <UpdateParameters>
    <asp:Parameter Name="Rut" />
    </UpdateParameters>


    <DeleteParameters>
    <asp:Parameter Name="Rut"/>
    </DeleteParameters>


    <SelectParameters>
    <asp:ControlParameter ControlID="DropDownList1" Name="Rut" PropertyName="SelectedValue"/>
    <asp:ControlParameter ControlID="DropDownList2" Name="IdProducto" PropertyName="SelectedValue"/>
    <asp:ControlParameter ControlID="DropDownList3" Name="IdCategoria" PropertyName="SelectedValue"/>
    <asp:ControlParameter ControlID="DropDownList4" Name="Experiencia" PropertyName="SelectedValue"/>
    </SelectParameters>


</asp:SqlDataSource>
<br />
<br />
<table>
<tr>
<td>Ingrese Rut</td>
<td>
<asp:TextBox ID="Rut" runat="server"></asp:TextBox>
</tr>
<td>Ingrese IdProducto</td>
<td>
<asp:TextBox ID="IdProducto" runat="server"></asp:TextBox>
</tr>
<td>Ingrese IdCategoria</td>
<td>
<asp:TextBox ID="IdCategoria" runat="server"></asp:TextBox>
</tr>
<td>Ingrese Experiencia</td>
<td>
<asp:TextBox ID="Experiencia" runat="server"></asp:TextBox>
</tr>
</table>


<asp:LinkButton ID="bInsert" runat="server" CausesValidation="True" CommandName="Insert" AutoPostBack="True" AppendDataBoundItems="true" enableviewstate="false" onclick="bInsert_Click"
    Text="Ingresar"></asp:LinkButton>


</form>



if you want to set a textbox's text property according to the selection change of dropdownlist then you can use 

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
         DataSourceID="SqlDataSource1"  AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" enableviewstate="false"
 DataTextField="Rut" DataValueField="Rut" DataTextFormatString="{0}">
 <asp:ListItem Value="0"><Select an option></asp:ListItem>
 <asp:ListItem Value="-1"><Select All></asp:ListItem>
 </asp:DropDownList>


 Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


                TextBox1.Text = DropDownList1.SelectedItem.Name
or
                TextBox1.Text = DropDownList1.SelectedValue
            

    End Sub




hi, thanks so much for answering, i changed my code to this :D


<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.OLEDB" %>
<%@ import Namespace="System.Data.OleDb.OleDbException" %>
<%@ Import Namespace="AjaxControlToolkit" %>
<script runat="server">
 

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
  

        TextBox.Text = DropDownList1.SelectedItem.Name
              

    End Sub
</script>


<form id="form1" runat="server">


<asp:LinkButton ID="LinkButton5" runat="server" Text="Default"
    PostBackUrl="http://localhost:49724/Default.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton4" runat="server" Text="Editar/Actualizar/Eliminar Empleado"
    PostBackUrl="http://localhost:49724/EditEmpleado.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton7" runat="server" Text="Editar/Actualizar/Eliminar Producto"
    PostBackUrl="http://localhost:49724/EditProducto.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton8" runat="server" Text="Editar/Actualizar/Eliminar Categoria"
    PostBackUrl="http://localhost:49724/EditCategoria.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton9" runat="server" Text="Editar/Actualizar/Eliminar Valores"
    PostBackUrl="http://localhost:49724/EditValores.aspx"></asp:LinkButton>
<br />
<asp:LinkButton ID="LinkButton10" runat="server" Text="Editar/Actualizar/Eliminar Conocimiento"
    PostBackUrl="http://localhost:49724/EditConocimiento.aspx"></asp:LinkButton>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT [PROJID] FROM [sxb_Proyectos] ORDER BY [PROJID]">
</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT DISTINCT Ax50_Empleados.rut, Ax50_HorasRegistradas.rut
                    FROM Ax50_Empleados
                    INNER JOIN Ax50_HorasRegistradas
                    ON Ax50_Empleados.rut= Ax50_HorasRegistradas.rut
                    where ([PROJID] = CASE WHEN @PROJID = '-1' THEN [PROJID] ELSE @PROJID END)
                    ORDER BY Ax50_Empleados.rut">


<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="PROJID" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>


<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
    SelectCommand="SELECT DISTINCT sxb_Producto.Producto, Ax50_HorasRegistradas.LINEPROPERTYID
                    FROM sxb_Producto
                    INNER JOIN Ax50_HorasRegistradas
                    ON sxb_Producto.Producto = Ax50_HorasRegistradas.LINEPROPERTYID
                    where (([rut] = CASE WHEN @rut=  '-1' THEN [rut] ELSE @rut END)
                    AND
                    ([PROJID] = CASE WHEN @PROJID = '-1' THEN [PROJID] ELSE @PROJID END))
                    ORDER BY sxb_Producto.Producto">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList2" Name="rut" PropertyName="SelectedValue"/>
<asp:ControlParameter ControlID="DropDownList1" Name="PROJID" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>


<table>
<tr>
<td>Proyecto</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1"  AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
DataTextField="PROJID" DataValueField="PROJID">
<asp:ListItem Value="0"><Select an option></asp:ListItem>
<asp:ListItem Value="-1"><Select All></asp:ListItem>
</asp:DropDownList>
</tr>


<tr>

this is the text box and the error

 

<td>
    <asp:textbox ID="textbox" runat="server" ReadOnly="True"></asp:textbox>
</td>

Mensaje de error del compilador: BC30456: 'Name' no es un miembro de 'System.Web.UI.WebControls.ListItem'.

Error de código fuente:

Línea 10: Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)  
Línea 11:   
Línea 12:         TextBox.Text = DropDownList1.SelectedItem.Name
Línea 13:               
Línea 14:     End Sub

Please use

DropDownList1.SelectedItem.Text

instead of

DropDownList1.SelectedItem.Name

Sorry for the misinformation

REAL NICE, thanks for your help, but now, how can i show in that Textbox, not the item that i selected, but an item that is in the same table where i get the data to fill the dropdownlist. All the data is in a LOCAL SQL SERVER. In me table i have serveral columns and with the first dropdownlist as you can see i select one. But in the textbox i want to show other column.

the table has

PROJID RUT LINEPROPERTYID QTY TXT TRANSDATE TRANSTATUS columns. The first dropdown select the PROJID columns and in the textbox i would like to show for example the LINEPROPERTYID data according for what i selected in the dropdownlist. 

thank you so much :D

[RESOLVED] Using REQUEST("ListBoxName") to get values

So I have a master page and inside it is a content place holder. In that content place holder is a panel with a bunch of multi select list boxes. Under that panel is a button.

when I click the button, I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine. Could you help explain what I am doing wrong??

This is a section of my code:


Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        

        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request.QueryString("MethodNameLB")
                

        If MethodIDSelection = "" Then
            Label5.Text = "Method was blank"
        Else
            Label5.Text = MethodIDSelection
        End If
        

    End Sub


According to your wording above the button is on the Content Page with the ListBoxes.  Are you passing the query string to this page and you simply want to pre-select the items in the list boxes or you want to generate a query string from the selections to pass to another page?

If you are trying to generate a comma separated list can we see the code you used to create the ListBoxes?  If it is data driven then be sure you are reloading the data after the postback.  I also do not see any code to even loop through the listboxes and create a list.  I do recommend StringBuilder instead of String with a simple += because it is more efficient.

Sudo Code:

Dim MyString As New StringBuilder


For Each Item As ListItem In MyListBox
     If Item.Selected Then
          MyString.Append("," & Item.Text)
     End If
Next


Response.Redirect("NewPage.aspx?selected=" & MyString.ToString, False)

If you are trying to read the query string the above code should be in the Me.Load method handler.  Once the button is clicked it initiates a postback and will most likely loose the query string.

Sorry page lost formatting so I deleted it.

Sorry, I guess I missed out some information. I didn't mean to use the .QueryString. Just use Request("MethodNameLB"). Also, the data in the listbox is from an object datasource attached to a database. Here is the code for the entire ASPX page. Its pretty straightforward.


<%@ Page Title="" Language="VB" MasterPageFile="~/SuperPage.master" %>


<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>


<script runat="server">
    

    Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)


        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request("MethodNameLB")
                

        If MethodIDSelection = "" Then
            MyLabel.Text = "Method was blank"
        Else
            MyLabel.Text = MethodIDSelection
        End If
        

    End Sub
    

</script>


<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="TitleContent" Runat="Server">
Test Page</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">


<div style="font-family: Verdana; font-size: small">
   

    <asp:ObjectDataSource ID="PersonalMethodsData" runat="server"
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetPersonalMethodsDataByActive"
            TypeName="PersonalMethodsBLL"></asp:ObjectDataSource>
            





    <asp:ListBox ID="MethodNameLB" runat="server" DataSourceID="PersonalMethodsData"
                            DataTextField="MethodName" DataValueField="PersonalMethodID"
                            SelectionMode="Multiple"></asp:ListBox>
    <cc1:ListSearchExtender ID="MethodNameLB_ListSearchExtender" runat="server" PromptCssClass="searchExtender"
                            PromptPosition="Bottom" PromptText=""
    TargetControlID="MethodNameLB">
    </cc1:ListSearchExtender>
    <br />
    <asp:Label ID="MyLabel" runat="server" Text="Label"></asp:Label>
<asp:Panel ID="InputPanel" runat="server">
</asp:Panel>
<asp:Button ID="FilterButton" runat="server" Text="Filter View" onclick="FilterButton_Click" />


</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ScriptHolder" Runat="Server"></asp:Content>


Using just Request(key) is not nearly as efficient as specifying the actual source.  The Request(key) command will look through the Request.Forms, Request.QueryString, Request.Cookies, and Request.ServerVariables just to find a match.  If you want the application to create a comma separate list I would suggest using a session variable to maintain the data and not the Request object.  You should use a ViewState if you only need the data on that page.  To create the list though you don't need to assign the object to anything until the end.

Now I am not too familiar with ObjectDataSource controls but I do know for the selected items to remain you need to reload the data on postback from the previous source and not reload the data each time from the database.  If you load it each time it will clear the checked items before it ever runs the button click event.  I always load data in a BindData method similar to the code below.  It allows for easier debugging and less web code.  Hope this helps point you in a different direction that works.

Dim myData As DataTable


Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
     If Not IsPostBack Then
          BindData(True)
     Else
          myData = CType(ViewState("TableData"), DataTable)
     End If
End Sub


Private Sub BindData(Optional ByVal RefreshData As Boolean = False)
     If RefreshData Then
          myData = GetPersonalMethodsDataByActive()
          ViewState("TableData") = myData
     End If


     MethodNameLB.DataSource = myData
     MethodNameLB.DataBind()
End Sub


Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFilter.Click
     Dim MyList As New StringBuilder
     For Each Item As ListItem In MethodNameLB
          If Item.Selected Then
               MyList.Append("," & Item.Value)
          End If
     Next
     If MyList.Length > 0 Then MyList.Remove(0, 1)
     Session("SelectedItems") = MyList.ToString
End Sub


 

This can be done without using Request object. Here's an example, which you may write in codebehind of your content page.


string strTemp1 = "";
foreach (ListItem item in ListBox1.Items)
{
     if (item.Selected == true)
     {
               
        strTemp1 += (strTemp1 == "") ? item.Value : "," + item.Value;
      }

I just figured using the request object would be easiest. But it doesn't seem to work if the listbox in inside of an update panel. My guess is because their is only a partial page postback and the request() never gets called.

My main goal is to try and simplify the code. I don't like the looping through method as it is messy and I have to due this on several list boxes. I have resorted to LINQ as an alternative but have ran into another problem I'm hoping someone can help me out with. I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

Anyhow this is what I have moved toward:

Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItemsText = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Text


Dim selItemsValue = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Value


TextString = Join(selItemsText.ToArray, ",")
ValueString = Join(selItemsValue.ToArray, ",")


'I would like to do this using 1 LINQ statement selecting separate entities like this:


Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItems = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select New With {.itemtext = li.Text, .itemVal = li.Value}


TextString = Join(selItems.itemtext.ToArray, ",")
ValueString = Join(selItems.itemVal.ToArray, ",")


I'm not sure if this is possible or not, or if my code is even accurate as I haven't tested it, but this is what I'm trying to accomplish. So if I had a listbox with the following data I would get the following strings:

listboxText - listboxValue - Selected

A - 1 - YES

B - 2 - NO

C - 3 - YES


TextString = "A,C"

ValueString = "1,3"




Note: I am using VB.net not C# or old versions of VB so an answer in VB.Net would be much appreciated. Thanks

Hi,

Hybird

I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine.
 

According to your description ,for my experience the Request object can retrieve the values that the client browser passed to the server during an HTTP request.

As far as I know you can use Request["nameOfControl"] to get control's value. 

However ,if you use a master page ,the name of control(which is contained in the content page) is not the same as its'ID.

Thus,the code which as you mentioned in your post :Request("MethodNameLB") can not get the value.

I would like to suggest you to check the sample below which shows how to use Request object to get the value of the control which is contained in content page.

1.Code in master page(.master):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


2.Code in content page(.aspx):

 

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:HiddenField ID="HiddenField1" runat="server" />
</asp:Content>


 

3.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            Response.Write(Request(listboxName).ToString())
        End If
    End Sub


 

 

Hybird

But it doesn't seem to work if the listbox in inside of an update panel.

Please just modify the code(in content page) which I mentioned above:

1.Code in content page(.aspx):

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>


 

2.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            'Show Result.
            Me.Label1.Text = Request(listboxName).ToString()
        End If
    End Sub


 

Hybird

I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

You can create an Entity class and pass the entity to an array as below:

Create a new page to demo the sample:

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


2.Code in page(.vb):

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Public list As New List(Of Items)()
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each item As ListItem In Me.ListBox1.Items
            If item.Selected Then
                Dim i As New Items()
                i.ID = item.Value
                i.Text = item.Text
                list.Add(i)
            End If
        Next

        ' Now you can the value like this:
        For Each listitem As Items In list
            Response.Write(("Text:" + listitem.Text & " value:") + listitem.ID & "<br/>")
        Next
    End Sub


End Class

' Entity Class 
Public Class Items
    Private _id As String
    Private _text As String

    Public Property ID() As String
        Get
            Return _id
        End Get
        Set(ByVal value As String)
            _id = value
        End Set
    End Property
    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property
End Class


Hope it can help you.

Wow, thank you Ming, that was an extremely informative post! Thanks for taking the time to actually create the test pages!

A note on some things I had to modify to get it working in case other people happen to stubble upon this informative post:

1.) in order to use the type datatable, at the top of your master page or content page you must include

<%@ Import Namespace="System.Data" %>

2.) I have a separate script content place holder where I generally place all of my scripts, and If I placed the

<script language="javascript" type="text/javascript">
          function GetNameOfListBox() {
              var listbox = document.getElementById("<%=ListBox1.ClientID %>");
              var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
              hidden.value = listbox.name;
          }  
 </script>

section of code in there it would not work. I had to place it in the same content place holder as the one where the hidden field is located.


Thanks again for your solution! Works wonders.

Selected Dynamic Menu item

I am trying to set the background color of a selected item in a dynamic dropdown menu.  I have a 10px horizontal padding on for the dropdown menu.  Some of the options in the menu are longer in word length.  I want to set the background color of a selected item across the entire width of the dropdown including the padding.  I have also tried setting padding in my css style sheet left and right but it doesn't give the desired effect because of the longer worded menu items.  At the moment I am only able to set the background color of the word itself in the dropdown menu.  On selected item the horizontal-padding goes back to 0 to incorporate the css padding.  I know this isn't the final solution but the issue still remains.  Any ideas?

Style sheet

.menubk TD /* Defines the entire menu background table */
{
  background-color:#2A2B64;
}
.menudynbkfor a /* Defines the top menu color and 'a' to override link default*/
{
  background-color:#2A2B64;
  color:#FFFFCC;
}
.menudynbk_select a /* Defines the dynamic selected item of menu color and 'a' to override link default*/
{
  background-color:#FFFFCC;
  color:#2A2B64;
  padding-left:10px;
  padding-right:10px;
}
.menudynbk TD /* Defines the dynamic dropdown menu color and 'TD' to override inherited table*/
{
  background-color:#2A2B64;
}


VB.Net Code

<asp:Menu ID="mnu" runat="server" CssClass="menudynbkfor"
                       DynamicEnableDefaultPopOutImage="False" DynamicHorizontalOffset="33" 
                        Orientation="Horizontal" StaticMenuItemStyle-HorizontalPadding="25" StaticEnableDefaultPopOutImage="False"
                        style="font-family: Arial, Helvetica, sans-serif">
                        <DynamicMenuItemStyle CssClass="menudynbkfor" HorizontalPadding="10px" ItemSpacing="5px" />
                        <DynamicMenuStyle CssClass="menudynbk" />
                        <DynamicSelectedStyle CssClass="menudynbk_select" HorizontalPadding="0px" />
                        <Items>
                            <asp:MenuItem Text="Publication" Value="Publication" Selectable="False">
                            <asp:MenuItem Text="Operational" Value="Operational"></asp:MenuItem>
                            <asp:MenuItem Text="System" Value="System"></asp:MenuItem>
                            <asp:MenuItem Text="Services" Value="Services"></asp:MenuItem>
                            </asp:MenuItem>
                            <asp:MenuItem Text="Rules" Value="Rules" Selectable="False">
                                <asp:MenuItem Text="Operational" Value="Operational" 
                                    ></asp:MenuItem>
                                <asp:MenuItem Text="Interface" Value="Interface"></asp:MenuItem>
                            </asp:MenuItem>
                            <asp:MenuItem Text="Interfaces" Value="Interfaces" Selectable="False">
                                <asp:MenuItem Text="System" Value="0"></asp:MenuItem>
                                <asp:MenuItem Text="System Pairs" Value="1"></asp:MenuItem>
                                <asp:MenuItem Text="Messages / Templates" Value="2">
                                </asp:MenuItem>
                                <asp:MenuItem Text="Elements" Value="3"></asp:MenuItem>
                            </asp:MenuItem>
                            <asp:MenuItem Text="Services" Value="Services" Selectable="False">
                            <asp:MenuItem Text="Providers" Value="Providers"></asp:MenuItem>
                            <asp:MenuItem Text="Services" Value="Services"></asp:MenuItem>
                            </asp:MenuItem>
                            <asp:MenuItem Text="Data Dictionary" Value="Data Dictionary"></asp:MenuItem>
                            <asp:MenuItem Text="Glossary" Value="Glossary" Selectable="False">
                                <asp:MenuItem Text="Acronyms" Value="Acronyms" ></asp:MenuItem>
                                <asp:MenuItem Text="Terminology" Value="Terminology"></asp:MenuItem>
                            </asp:MenuItem>
                        </Items>
                    </asp:Menu>