Category Archives: App_Code

[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!

User Control... one strange problem…

Hi,

One strange problem…

I’ve developed one user control for all countries list. Here is the code…

CountryControlBase.vb in App_Code folder
---------------------------------------
Imports Microsoft.VisualBasic
Namespace BlueSky.UserControls
    Public Class CountryControlBase
        Inherits UserControl
        Public Sub New()
            MyBase.New()
        End Sub
        Public Overridable Property Text() As String
            Get
                Return "selected value"
            End Get
            Set(ByVal value As String)
                'child class will override this implementation...
            End Set
        End Property
    End Class
End Namespace
----------------------------------------

--------------------------
CountryControl.ascx
---------------------
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="CountryControl.ascx.vb" Inherits="CountryControl" %>

<asp:DropDownList ID=ddlCountries Runat=server
EnableViewState=True></asp:DropDownList>

<asp:RequiredFieldValidator ID="ddlCountriesRequiredFieldValidator" ControlToValidate="ddlCountries" runat="server" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
---------------------------------------------------

---------------------------------------------------
CountryControl.ascx.vb
-----------------------------------------------
Imports System.Xml
Imports System.Data
Partial Class CountryControl
    Inherits BlueSky.UserControls.CountryControlBase

    Public Sub New()
        MyBase.new()
    End Sub

    Protected _validate As Boolean

    Public Property Validate() As Boolean
        Get
            Return _validate
        End Get
        Set(ByVal value As Boolean)
            _validate = value
        End Set
    End Property

    Public Overrides Property Text() As String
        Get
            Return ddlCountries.SelectedValue
        End Get
        Set(ByVal Value As String)
            ddlCountries.SelectedValue = Value
        End Set
    End Property

    Private Function UCFirst(ByVal str As String) As String
        str = str.ToLower
        Dim chrFirst As Char
        chrFirst = CType(str.Substring(0, 1), Char)
        chrFirst = CType(chrFirst.ToString.ToUpper, Char)
        str = chrFirst & str.Substring(1, str.Length - 1)

        Return str

    End Function

    Private Function ProperCaseFormat(ByVal str As String) As String
        Return StrConv(str, VbStrConv.ProperCase)
    End Function

    Private Sub generateCountries()
        Dim ds As New DataSet
        Dim i As Integer
        Try
            ds.ReadXml(MapPath("countries.xml"))
            ddlCountries.Items.Add("")
            For i = 0 To ds.Tables(0).Rows.Count - 1
                ddlCountries.Items.Add(ProperCaseFormat(CType(ds.Tables(0).Rows(i).Item(0), String).ToLower))
            Next

        Catch ex As Exception
            Response.Write(ex.Message)
        End Try

        ddlCountries.SelectedValue = Text
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        generateCountries()
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        ddlCountriesRequiredFieldValidator.Enabled = _validate
    End Sub

End Class
-----------------------------------------------------------------------------------------------------------

Now I am using this user control in one of my aspx page like this…
The register statement at the top of the page…
-------------------------
Countries.aspx
-------------------------
<%@ Register TagPrefix="uc" TagName="Country" Src="~/UserControls/Country/CountryControl.ascx" %>
----------------------------
and in between like this...
-------------------------
<uc:Country Id="ddlCountries" runat=Server Validate=False></uc:Country>
--------------------------

Now the problem is that, when I am trying to access this control in codefile…
---------------------
Countries.aspx.vb
---------------------
 Dim c As Control
        c = CType(Me.FindControl("ddlCountries"), BlueSky.UserControls.CountryControlBase)
 Dim country as String
 country = c.Text
-------------------------

But mysteriously… the FindControl is not returning a reference to the control added in the web page and I am getting a “Object reference not set to an instance of an object.” Error.

I am using VB.Net as language and .Net Framework 2.0 with Visual Studio 2005 beta 2 releases.


Please help me…

Thanks,
-Lalit

 

 

IS your aspx page inside master page ?if so you need find control inisde master like this.Page.Master.FindControl("ddlCountries");

Also try and find "ddlCountries" in page source for making sure its present somewhere :)

[RESOLVED] Reference user control from a .vb class in the app_code directory

Hi, i've created a user control and i want to have an instance of it passed to a Method in my app_code folder.

Bassically this is what i need(SomeName.vb):

 

Public Shared Sub SomeName(myc as SomeUserControl)


'Some code here

End Sub

 

Please Note that the above file is located in the app_code directory, and the user control is not.

Thanks.

to make the usercontrols specific Type available to your app_code class/method, you can:

  1. <div mce_keep="true">move the usercontrols codebehind file into your app_code folder</div>
  2. <div mce_keep="true">change the usercontrols control declaration to point to the new code location</div>

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="~/app_code/usercontrols/YourUserControl.ascx.vb" Inherits="YourUserControl" %>

In addition to making the usercontrols type available to your app_code classes, your usercontrols type is now also available to all other pages/control in your web.  this is often a convenient way to be able to deal with dynamically created users controls in a strongly typed way even if they have not been drag/dropped onto a page.

 

In addition to Mikes post you could abstract the methods and properties that you really want to access from the UC (User Control) into an abstract / must inherit base class.

This base class would inherit from UserControl and the UC instance would inherit from the Base Class. The base class defintion / code would be in the APP_Code folder, or a referenced library, and the parameter for the functions in the other classes would of the base class type. You could also use an interface, but a base class is likely more appropriate.

The benefit of this approach is that VS will still integrate seamlessly with the code behind file for the UC instance.

About Mike's post, this line:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="~/app_code/usercontrols/YourUserControl.ascx.vb" Inherits="YourUserControl" %>

Does not work for me.  If I create a UserControl, and put it's code behind file in my app_code folder as shown above, (obviously which folder inside the app_code that it's in doesn't matter) I get the following error while building the site:

"The file <relative path to file> is in the special directory 'App_Code', which is not allowed."

Am I doing something wrong?  I read somewhere that it doesn't work with regular websites, you have to have a Web Application Project.  Is that what's wrong?  I have been beating my brains out to try and figure out how to instantiate a UserControl from a codebehind file of a .aspx page in order to dynamically set properties in it and send an HTML email with the UserControl as the HTML template.  I have come to a whoppin road block as nothing works for me in all the examples that I see (it appears that way anyway).

mokeefe

you could abstract the methods and properties that you really want to access from the UC (User Control) into an abstract / must inherit base class.

Martin's solution is what I've seen most-often suggested in similar posts.. (sometimes other people suggest an interface instead of an abstract class, but I believe abstract class is a better way to go, since it enforces the "IS A" relationship).  

Does anybody know if there are any adverse affects to creating these "extra" classes in App_Code?  

[RESOLVED] rebinding a GridView after delete

 

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Data.SqlClient;

namespace Maine_Innkeeper_Site_2010.cms.member
{
    public partial class industry_supplier : System.Web.UI.Page
    {

        // establish the db connection string
        string cnstr = common.dbConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ViewState["SelectedText"] = "All";
                CreateAlphaPagings();
                BindGrid(this.ViewState["SelectedText"].ToString());
            }
        }

        //alphabetical paging
        private void CreateAlphaPagings()
        {
            //create a new datatable to hold the paging content
            DataTable dt = new DataTable();

            if (this.ViewState["Paging"] == null)
            {
                SqlDataAdapter da = new SqlDataAdapter("paging_sproc_suppliers", cnstr);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.Add("@OptionId", SqlDbType.Int).Value = 2;
                da.Fill(dt);
                this.ViewState["Paging"] = dt;
            }
            else
                dt = (DataTable)this.ViewState["Paging"];

            DataList1.DataSource = dt;
            DataList1.DataBind();
        }

        private void BindGrid(string StartAlpha)
        {
            string sql = "";

            if (StartAlpha == "All")
                sql = "SELECT id, organization_name, date_added FROM industry_suppliers ORDER BY organization_name";
            else
                sql = "SELECT id, organization_name, date_added FROM industry_suppliers WHERE organization_name LIKE '" + StartAlpha + "%' ORDER BY organization_name";

            SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
            DataTable dtSelect = new DataTable();
            da.Fill(dtSelect);

            GridView1.DataSource = dtSelect;
            GridView1.DataBind();
        }

        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            LinkButton lbkbtnPaging = (LinkButton)e.CommandSource;
            BindGrid(e.CommandArgument.ToString());
            this.ViewState["SelectedText"] = e.CommandArgument.ToString();
            CreateAlphaPagings();
        }

        protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                if (this.ViewState["SelectedText"] != null)
                {
                    LinkButton lbkbtnPaging = (LinkButton)e.Item.FindControl("lnkbtnPaging");
                    if (this.ViewState["SelectedText"].ToString() == lbkbtnPaging.Text)
                        lbkbtnPaging.Enabled = false;
                }
            }
        }

        //delete the row selected from the database table
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //first declare a new instance of the TableAdapter
            App_Code.DataAccessLayer.MaineInnsDataset maineinnsDataset = new App_Code.DataAccessLayer.MaineInnsDataset();
            App_Code.DataAccessLayer.MaineInnsDatasetTableAdapters.industry_suppliersTableAdapter Industry_SuppliersTableAdapter =
            new App_Code.DataAccessLayer.MaineInnsDatasetTableAdapters.industry_suppliersTableAdapter();
            
            //establish the id parameter from the GridView row
            int id = (int)GridView1.DataKeys[e.RowIndex].Value;
            
            //now delete the record
            Industry_SuppliersTableAdapter.DeleteSupplier(id);
        }

        protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            // rebind the GridView
            GridView1.DataBind();

            //display a "success" message
            Label1.Text = "Supplier deleted.";
            Label1.Visible = true;
        }
    }
}

I created a GridView that uses a custom paging method that allows for alphabetical paging. I seem to be having some problems now rebinding the GridView after a delete occurs. The row is deleted, it's just that the rebinding doesn't happen so to the user it looks like the delete failed. Been over and over my code and can't understand why. See the final block which is supposed to fire on the GridView1_ItemDeleted event.

 

Looks like you're not using a data source control. 

Provide the DataSource before you execute .DataBind() 

* like you've done with the BindGrid() method, OR call it instead

Thanks. So you mean, instead of using this in that last code block:

// rebind the GridView
GridView1.DataBind();

Do this:

BindGrid(string StartAlpha);

Is that correct? So in effect I'm calling the "BindGrid" method again after the RowDeleted event fires.

Apparently I'm not calling the BindGrid method correctly, as Visual Studio is telling me "invalid expression term 'String'"

How do I correctly call BindGrid here? Thanks.

Mister Ed

BindGrid(string StartAlpha);

right, but you need to pass the value, which value you're storing in the ViewState variable 

see, as:

BindGrid(this.ViewState["SelectedText"].ToString());

Thank you very much.

It's still not rebinding after the delete occurs (and I can see that the row is deleted from the db table), and I notice that the "success" message is also not appearing. Which leads me to suspect my code is somehow not firing with the RowDeleted event. I've gone over it several times and everything appears correct, though--or am I missing something obvious here?

The Gridview attributes specify a method to employ for the OnRowDeleted event:

OnRowDeleted="GridView1_RowDeleted"

And then the method in Code behind is this:

 protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            // rebind the GridView
            BindGrid(this.ViewState["SelectedText"].ToString());

            //display a "success" message
            Label1.Text = "Supplier deleted.";
            Label1.Visible = true;
        }

Why isn't this firing?

[RESOLVED] web.config sessionState other than "Off" ignores "roles" in web.sitemap

I changed my application to use "InProc" sessionState instead of "Off" because I need to preserve user selected language from page to page doing localization.

In web.sitemap I have this line:

  <siteMapNode url="Admin.aspx" title="Administrator" description="Site administration" roles="Administrator" />

which before I changed sessionState to "InProc" worked as supposed to: menu item "Administrator" appeared as a menu choice only when user had logged in with admin rights. Now this menu choice is present for every user.

What could be reason behind this?

P.S. I derive every page from my BasePage.cs in App_Code directory overriding InitializeCulture method.

 

Are you calling Session.Abandon() as part of your logoff process?

The roles attribute doesn't do what you think. We all fell into this trap. Read http://blogs.ipona.com/davids/archive/2009/01/12/8554.aspx.

Roles are also stored in a cookie, for performance reasons. You can turn this off if you need to in web.config, in the roles section, with cacheRolesInCookie="false". The real problem is the roles attribute though.

I was not using cookies:

<sessionState mode="InProc" cookieless="true" timeout="60"/>

After this it worked:

<sessionState mode="InProc" cookieless="false" timeout="60"/>

 

Thanks, Timo