Category Archives: SqlDataSource

[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] Populating a dynamically generated checklist control in code-behind not working

<div style="margin-top: 8px; margin-right: 8px; margin-bottom: 8px; margin-left: 8px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: rgb(255, 255, 255); " mce_style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; margin-top: 8px; margin-right: 8px; margin-bottom: 8px; margin-left: 8px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #ffffff; ">

(The following is a complete re-edit of the original post which was rambling, confusing etc...)

I have a form with a dynamically generated checklist:

<asp:CheckBoxList ID="cblGames" runat="server" DataSourceID="sqlGames" DataTextField="Game" DataValueField="Id" </asp:CheckBoxList>

 <asp:SqlDataSource ID="sqlGames" runat="server" ConnectionString="<%$ ConnectionStrings:Games %>" 

SelectCommand="SELECT [Id], [Game], [ShowWaitingList] FROM [Aanbod] WHERE ([ShowWaitingList] = @ShowWaitingList)">

 <SelectParameters><asp:Parameter DefaultValue="true" Name="ShowWaitingList" Type="Boolean" /></SelectParameters>

</asp:SqlDataSource>

The following code-behind is supposed to check those boxes that correspond to values stored in a database. It fails and I don't know why. Any ideas?

regards, Guy (p.s. [AanbodId] and [Id] are equivalent.)


if    (!Page.IsPostBack && Request.QueryString["id"] != null)
        {
               // Code that gets the data goes here. Removed for brevity's sake //
              ListItem currentCheckBox = cblGames.Items.FindByValue(reader["AanbodId"].ToString());
              if (currentCheckBox != null)
              {
                  currentCheckBox.Selected = true;
              }
             

            }
        }


</div>


First of all, here's a tip using the Insert Code tool:  Once you've inserted a code block, don't edit it.  That's probably how you ended up with all those spurious <SPAN> tags in your C#.  (No disrespect intended - just something I had to learn the hard way.)

Secondly, .aspx pages by default post back to themselves, so you shouln't need to redirect a page back to itself.  If you use Response.Redirect to do that, you'll loose all the information saved in viewstate, which may or may not explain why you're having this problem.

HI, (this post can be ignored, see re-edit above)


I tried to edit the code down because it's a little convoluted (I'm a newbie) and I hoped just presenting the key  would make it easier to understand the problem. I'm sure those span tags didn't show in the preview!


Anyway, the page only redirects after a new record is inserted. This insures that the user is presented with a blank form to enter the next record. I see the usefulness of viewstate for many tasks, but think it less than useful for database inserts which most of the time involve moving onto the next record. I considered resetting all entry fields to blanks in the code behind, but a redirect is simpler (if not  exactly elegant).

So I am still stuck with the original problem. Is it clear what I want to be done and what the problem is?

Both scenarios/solutions I've tried take place with viewstate (not that it is used). Neither give me the result I want.


regards, Guy

Are you running the above code in the CheckBoxList.DataBound handler or where?  (It won't work before that event.)

(And you're right about preview mode; it's useless.  You just have to learn the hard way, like all of us, that the code block starts and ends with the two blank lines above and below the code, and that once you click Insert, the only safe way to edit it is in HTML mode.  And even in HTML mode, you can't put HTML tags between the <PRE> and </PRE> tags.)

[RESOLVED] Url Routing in .net 4.0 and 3.5

Hello,

    I am trying to implement Url routing in 4.0 by following example http://www.dotnetspark.com/kb/2369-step-by-step-tutorial-on-url-routing-asp-net.aspx

Works fine..

Now the scenario is that i have gridview with object datasource which accepts  "Name" as query string.

<asp:gridview ID="Gridview1" runat="server" DataSourceID="ObjectDataSource1"></asp:gridview>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
            OldValuesParameterFormatString="original_{0}" SelectMethod="Hello"
            TypeName="WebApplication2.Class.MethodsTest">
            <SelectParameters>
                <asp:QueryStringParameter Name="value" QueryStringField="Name" Type="String" />
            </SelectParameters>
        </asp:ObjectDataSource>

i tried this code. But i couldn't get the value in QueryString Field??

How to handle in this situation??

+

How to implement (the link example in net 3.5)??? because i don't  "

routes.MapPageRoute


" attribute in  3.5. i have few existing application in 3.5 so thought of implementing there too.


Please guide me..This example in Link looks very easy and simple to handle


Thanks....

if your getting the value parameter from a pageroute you cant use querystring you should use a Route Parameter something like this.

<asp:RouteParameter RouteKey="Name" Name="value" Type="String" />

here you have another example how to do it... http://weblogs.asp.net/hajan/archive/2010/10/15/url-routing-in-asp-net-4-0-web-forms.aspx

In his example he is showing a codebehind example of how to access the route but in my example show you how to use it...

Hope it helps....
 

So you mean to say that i can't use querystring for passing value to objectsource???

How to pass the value objectsource then???

In your link you have shown it in asp.net 3.5 sp1. right??

But how to pass value on click of the Button? like he has shown in the example (mine link).


because in my scenario i have to pass value through querystring in many places...so before i implement this feature i need to know how to access the value in pass it in objectdatasource and i don't want to use code behind.

i just checked on net http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx

Is the

<asp:routeparameter name="category" RouteKey="category" />

not available for 3.5 sp1 in webforms???

Thanks.




Im not sure if it works in 3.5 I upgraded all my apps to 4.0 when implementing routing. 

If you use url routing the routeparameter replaces querystring. the querystring fetches the parameter after the questionmark (?) in the url and when using routing you dont have it. 

 

i could see few example with routing stuff in asp.net 3.5 but i am not able to get  <asp:routeparameter in my html.



indeed this is why I choose to wait with moving from URL rewrite to URL routing until I moved to ASP.NET 4.0 even finding answers for URL Routing 4.0 is difficult if your not working with MVC and want some info covering more than the basic's

this works with ASP.NET 4.0 but if the <asp:routeparameter is not supported in asp.net 3.5 I can only see that you have to declare it in codebehind if you want it to work with you SqlDataSource.

 

ok i made one small application in 4.0 now and implemented Url routing in that and hosted in IIS in my machine (win 7).

but i get an error

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

now what could be the reason...when i am running with my visual studio then it works fine but when i hosted in IIS then i landed in above problem.

code i use.

protected void Application_Start(object sender, EventArgs e)
        {
            CustomRouteTable(RouteTable.Routes);
        }


   void CustomRouteTable(RouteCollection routes)
        {
           

            routes.MapPageRoute("Telugu", "Movie/Telugu", "~/Telugu/Telugu.aspx");
        }

and in my default.aspx i kept a button on click of the button i wrote:

 protected void btnTelugu_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectToRoute("Telugu");
        }


now where am i going wrong????

please guide me...


Hi,

abhishek0410

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

 

It seems that IIS can not handle the UrlRoute when you enter the route url in browser.

I think you need to check the .NET framework version of the web site application pool. Url Route module need .NET 3.5 or upon.

Open the IIS manager and check it.

How to check the .NET version on IIS7:

http://www.west-wind.com/weblog/posts/289139.aspx

http://technet.microsoft.com/en-us/library/cc754523(WS.10).aspx

Or add the UrlRoutingModule in web.config:

Check this link:

http://msdn.microsoft.com/en-us/library/cc668202(v=vs.90).aspx

Hope this can help you.

Well do you have a file with the path ~/telugu/telugu.aspx because that is what you pointing at!

my guess would be that not...

 routes.MapPageRoute("Telugu", _ //routename

"Movie/Telugu", _  // you have hardcoded a virtual path and it is not expecting any paramenters parameter should be within {}

"~/Telugu/Telugu.aspx"); // this is the physical path...

--------------------------------------

let say you hav a file Movie.aspx in your root folder and you want to have a url that is movie / title .aspx it the route you should register is like this

routes.MapPageRoute("MovieRoute""Movie/{title}""~/Movie.aspx");

and then for the url to redirect correctly with a given parameter it should be something like this  

RedirectToAction("title", "Movie"); // Action, Controller
RedirectToRoute("MovieRoute"); // Route name or like this if it is to a route without a parameter

hope it helped a little

[RESOLVED] ImageButton always calls page_load event....

I'm using ASP.NET 3.5 and C#.

I load an SqlDataSource into a DataView on my Page_Load event. My SqlDataSource queries a random record from the database. On my page I have an ImageButton, which when clicked uses a Response.Redirect("AnotherPage.aspx + "random id from database"). My problem is that when the button is clicked it fires the Page_Load event before the Response.Redirect takes place in the button_click event. This causes the current data(the users "id") that I had pulled from the database to be overwritten with new data(a different "id") from the database. So essentially the the page is redirecting to the 2nd random id that is queried from the db after the button is clicked and Page_Load is fired again, not the original id. Here's my code, hope it makes sense.

Here's my Page_Load:

DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);


id = dv[0]["Id"].ToString();


Then my Button_Click Event:

protected void btn1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("~/Profile.aspx?id=" + id1);
    }

Can I put my dataview in another event or method so it's not called when a user clicks an ImageButton. Also I want the DataView to be repopulated on a postback/page refresh, just not on button clicks. How?


Hi,

The page life cycle will work like that only.

In the Page_Load event you need to use Page.IsPostBack checking to ensure that during the post back it does not update the original value.

So fetching of the random id should be as below

in Page_Load event , give this condition

if (!Page.IsPostBack) {

    randomID = your code;

}


If Not IsPostBack on Page load will solve your problem